package com.controller.device;

import com.common.ErrorCodeEnum;
import com.common.anntation.Log;
import com.common.emums.BusinessType;
import com.common.excel.ExcelUtil;
import com.common.exception.BusinessException;
import com.common.utils.*;
import com.common.utils.file.FileUtils;
import com.common.utils.test.SocketTest;
import com.common.utils.uuid.IdUtils;
import com.core.springSecurity.common.SecurityUtils;
import com.core.springSecurity.model.LoginUserDetails;
import com.github.pagehelper.PageInfo;
import com.model.base.PageResult;
import com.model.base.Result;
import com.model.domain.data.GetDataObdTcpLogInfoDO;
import com.model.domain.device.*;
import com.model.domain.system.GetSystemDeviceModelInfoDO;
import com.model.domain.system.GetSystemDomainInfoDO;
import com.model.dto.device.deviceOBDInfo.*;
import com.model.pojo.data.DataObdTcpLogInfo;
import com.model.pojo.device.*;
import com.model.pojo.sys.SysUser;
import com.model.pojo.system.SimInfo;
import com.model.pojo.system.SystemDeviceModelInfo;
import com.model.pojo.system.SystemDomainInfo;
import com.model.pojo.user.UserInfo;
import com.model.vo.device.deviceOBDInfo.ExportBindDeviceListVO;
import com.model.vo.device.deviceOBDInfo.bindFactory.BindFactoryVO;
import com.model.vo.device.deviceOBDInfo.bindFactory.ErrorBindFactoryVO;
import com.model.vo.device.deviceOBDInfo.exportDeviceListByBatch.ExportDeviceListByBatchVO;
import com.model.vo.device.deviceOBDInfo.exportDeviceListByCarton.ExportDeviceListByCartonVO;
import com.model.vo.device.deviceOBDInfo.get25ObdList.Get25ObdListVO;
import com.model.vo.device.deviceOBDInfo.getActivationDataInDay.GetActivationDataInDayVO;
import com.model.vo.device.deviceOBDInfo.getBatchList.GetBatchListVO;
import com.model.vo.device.deviceOBDInfo.getBindListByBatchId.GetBindListByBatchIdVO;
import com.model.vo.device.deviceOBDInfo.getDatianIPList.GetDatianIPListVO;
import com.model.vo.device.deviceOBDInfo.getDeviceInfoByScan.GetDeviceInfoByScanDeviceVO;
import com.model.vo.device.deviceOBDInfo.getDeviceInfoByScan.GetDeviceInfoByScanVO;
import com.model.vo.device.deviceOBDInfo.getDeviceList.GetDeviceDistributionInAppVO;
import com.model.vo.device.deviceOBDInfo.getDeviceList.GetDeviceListVO;
import com.model.vo.device.deviceOBDInfo.getDeviceListByCarton.GetDeviceListByCartonVO;
import com.model.vo.device.deviceOBDInfo.getExFactoryBatchInfo.GetExFactoryBatchInfoVO;
import com.model.vo.device.deviceOBDInfo.getGpsMonitorList.GetGpsMonitorListVO;
import com.model.vo.device.deviceOBDInfo.getOnLineDataInDay.GetOnLineDataInDayVO;
import com.model.vo.device.deviceOBDInfo.getRepairBatchList.GetRepairBatchListVO;
import com.model.vo.device.deviceOBDInfo.getStatisticsInfo.GetStatisticsInfoVO;
import com.model.vo.device.deviceOBDInfo.getVersionList.GetVersionListVO;
import com.model.vo.device.deviceOBDInfo.getVersionListInAPP.GetVersionListInAPPVO;
import com.model.vo.device.deviceOBDInfo.saveRepairInfo.SaveRepairInfoVO;
import com.model.vo.device.deviceOBDInfo.scanBeforeExFactory.ScanBeforeExFactoryDeviceVO;
import com.model.vo.device.deviceOBDInfo.scanBeforeExFactory.ScanBeforeExFactoryVO;
import com.model.vo.device.deviceOBDInfo.scanCartonOnUpdateInfoInApp.ScanCartonNoUpdateInfoInAppVO;
import com.model.vo.device.deviceOBDInfo.scanUpdateInfo.ScanUpdateInfoVO;
import com.model.vo.device.deviceOBDInfo.scanUpdateInfoInApp.ScanUpdateInfoInAppVO;
import com.model.vo.device.deviceOBDInfo.searchNearDevice.SearchNearDeviceVO;
import com.model.vo.device.deviceOBDInfo.searchUpdateInfo.SearchUpdateInfoDeviceVO;
import com.model.vo.device.deviceOBDInfo.searchUpdateInfo.SearchUpdateInfoVO;
import com.model.vo.device.deviceOBDInfo.statisticsSimExpireInfo.StatisticsSimExpireInfoVO;
import com.model.vo.device.deviceOBDInfo.vail3Code.Vail3CodeVO;
import com.service.data.DataObdTcpLogInfoService;
import com.service.device.*;
import com.service.sys.SysUserService;
import com.service.system.SimInfoService;
import com.service.system.SystemDeviceModelInfoService;
import com.service.system.SystemDomainInfoService;
import com.service.user.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Description
 * @Author tm
 * @Date 2023-06-07 1:10
 **/
@Api(tags = {"OBD终端管理"})
@Slf4j
@RestController
@RequestMapping("/v1/device/obd")
@RequiredArgsConstructor
public class DeviceOBDInfoController {
    private final DeviceObdBaseInfoService deviceObdBaseInfoService;
    private final DeviceObdRepairRecordInfoService deviceObdRepairRecordInfoService;
    private final DeviceObdExFactoryBatchInfoService deviceObdExFactoryBatchInfoService;
    private final DeviceObdExFactoryScanRecordInfoService deviceObdExFactoryScanRecordInfoService;
    private final Device25ObdInfoService device25ObdInfoService;
    private final DeviceObdGpsInfoService deviceObdGpsInfoService;
    private final DeviceObdVersionInfoService deviceObdVersionInfoService;
    private final SysUserService sysUserService;
    private final SimInfoService simInfoService;
    private final UserInfoService userInfoService;
    private final DeviceObdTcpLogInfoService deviceObdTcpLogInfoService;
    private final DataObdTcpLogInfoService dataObdTcpLogInfoService;
    private final SystemDomainInfoService systemDomainInfoService;
    private final SystemDeviceModelInfoService systemDeviceModelInfoService;
    private final DeviceObdExFactoryBatchBindInfoService deviceObdExFactoryBatchBindInfoService;
    private final Device25ObdIpMonitorInfoService device25ObdIpMonitorInfoService;
    private final DeviceObdWorkDailyRecordInfoService deviceObdWorkDailyRecordInfoService;
    private final DeviceObdRepairExFactoryBatchInfoService deviceObdRepairExFactoryBatchInfoService;
    private final DeviceObdBatchRepairRecordInfoService deviceObdBatchRepairRecordInfoService;
    private final DeviceObdBatchRepairRecordMappingInfoService deviceObdBatchRepairRecordMappingInfoService;
    @Log(title = "OBD终端管理-终端统计信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "终端统计信息")
    @PostMapping("/getStatisticsInfo")
    public Result<GetStatisticsInfoVO> getStatisticsInfo(@RequestBody @Valid GetStatisticsInfoDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        Integer total = 0;
        Integer online = 0;
        Integer offline = 0;
        Integer activate = 0;
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        if (dto.getFactoryId() != null) {
            UserInfo userInfo = userInfoService.getById(dto.getFactoryId());
            if (userInfo != null && userInfo.getAllowSecondSupply() == 1) {//如果筛选的厂家的是可以二次供销的
                getDeviceObdBaseInfoDO.setFactoryUserId(null);
                List<Long> batchIds = new ArrayList<>();
                GetDeviceObdExFactoryBatchInfoDO getDeviceObdExFactoryBatchInfoDO = new GetDeviceObdExFactoryBatchInfoDO();
                getDeviceObdExFactoryBatchInfoDO.setFactoryUserId(dto.getFactoryId());
                getDeviceObdExFactoryBatchInfoDO.setSortRow("createTime");
                List<DeviceObdExFactoryBatchInfo> batchList = deviceObdExFactoryBatchInfoService.getAllList(getDeviceObdExFactoryBatchInfoDO);
                if (batchList != null && batchList.size() > 0) {
                    batchIds = batchList.stream().map(DeviceObdExFactoryBatchInfo::getBatchId).collect(Collectors.toList());
                } else {
                    batchIds.add(0l);
                }
                getDeviceObdBaseInfoDO.setBatchIds(batchIds);
            } else {
                getDeviceObdBaseInfoDO.setFactoryUserId(dto.getFactoryId());
            }
        }
        if ((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_厂家配置) && !"testadmin".equals(sysUser.getName()) && sysUser.getUserId() != null) {
            if(getDeviceObdBaseInfoDO.getFactoryUserId()==null)getDeviceObdBaseInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        //特殊处理
        if ("15210999919".equals(sysUser.getName())) {
            getDeviceObdBaseInfoDO.setFactoryUserId(null);
            getDeviceObdBaseInfoDO.setPrefix("02");
        }
        //处理可二次销售厂家的情况
        if((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 ||sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2) && sysUser.getUserId()!=null){
            UserInfo userInfo = userInfoService.getById(sysUser.getUserId());
            if (userInfo != null && userInfo.getAllowSecondSupply() == 1) {
                getDeviceObdBaseInfoDO.setFactoryUserId(null);
                List<Long> batchIds = new ArrayList<>();
                GetDeviceObdExFactoryBatchInfoDO getDeviceObdExFactoryBatchInfoDO = new GetDeviceObdExFactoryBatchInfoDO();
                getDeviceObdExFactoryBatchInfoDO.setFactoryUserId(sysUser.getUserId());
                getDeviceObdExFactoryBatchInfoDO.setSortRow("createTime");
                List<DeviceObdExFactoryBatchInfo> batchList = deviceObdExFactoryBatchInfoService.getAllList(getDeviceObdExFactoryBatchInfoDO);
                if (batchList != null && batchList.size() > 0) {
                    batchIds = batchList.stream().map(DeviceObdExFactoryBatchInfo::getBatchId).collect(Collectors.toList());
                } else {
                    batchIds.add(0l);
                }
                getDeviceObdBaseInfoDO.setBatchIds(batchIds);
            }
        }
        List<DeviceObdBaseInfo> deviceList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            total = deviceList.size();
            for (DeviceObdBaseInfo baseInfo : deviceList) {
                if (baseInfo.getOnLineStatus() == null || baseInfo.getOnLineStatus() == 0) {
                    offline++;
                } else online++;
                if (baseInfo.getHasActivation() != null && baseInfo.getHasActivation() == 1) {
                    activate++;
                }
            }
        }
        GetStatisticsInfoVO vo = new GetStatisticsInfoVO();
        vo.setTotal(total);
        vo.setOffline(offline);
        vo.setOnline(online);
        vo.setActivate(activate);
        return Result.suc(vo);
    }

    @Log(title = "OBD终端管理-终端列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "终端列表")
    @PostMapping("/getDeviceList")
    public Result<PageResult<List<GetDeviceListVO>>> getDeviceList(@RequestBody @Valid GetDeviceListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetDeviceListVO> voList = new ArrayList<>();
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdBaseInfoDO.class);
        if (dto.getCartonNo() != null && !"".equals(dto.getCartonNo())) {
            getDeviceObdBaseInfoDO.setCartonNo(null);
            getDeviceObdBaseInfoDO.setCartonNoLike(dto.getCartonNo());
        }
        if (dto.getFactoryId() != null) {
            UserInfo userInfo = userInfoService.getById(dto.getFactoryId());
            if (userInfo != null && userInfo.getAllowSecondSupply() == 1) {
                getDeviceObdBaseInfoDO.setFactoryUserId(null);
                List<Long> batchIds = new ArrayList<>();
                GetDeviceObdExFactoryBatchInfoDO getDeviceObdExFactoryBatchInfoDO = new GetDeviceObdExFactoryBatchInfoDO();
                getDeviceObdExFactoryBatchInfoDO.setFactoryUserId(dto.getFactoryId());
                getDeviceObdExFactoryBatchInfoDO.setSortRow("createTime");
                List<DeviceObdExFactoryBatchInfo> batchList = deviceObdExFactoryBatchInfoService.getAllList(getDeviceObdExFactoryBatchInfoDO);
                if (batchList != null && batchList.size() > 0) {
                    batchIds = batchList.stream().map(DeviceObdExFactoryBatchInfo::getBatchId).collect(Collectors.toList());
                } else {
                    batchIds.add(0l);
                }
                getDeviceObdBaseInfoDO.setBatchIds(batchIds);
            } else {
                getDeviceObdBaseInfoDO.setFactoryUserId(dto.getFactoryId());
            }
        }
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        if ((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_厂家配置) && !"testadmin".equals(sysUser.getName()) && sysUser.getUserId() != null) {
            if(getDeviceObdBaseInfoDO.getFactoryUserId() == null)getDeviceObdBaseInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        //特殊处理
        if ("15210999919".equals(sysUser.getName())) {
            getDeviceObdBaseInfoDO.setFactoryUserId(null);
            getDeviceObdBaseInfoDO.setPrefix("02");
        }
        //处理可二次销售厂家的情况
        if((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 ||sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2) && sysUser.getUserId()!=null){
            UserInfo userInfo = userInfoService.getById(sysUser.getUserId());
            if(userInfo!=null && userInfo.getAllowSecondSupply() == 1){
                getDeviceObdBaseInfoDO.setFactoryUserId(null);
                List<Long> batchIds  = new ArrayList<>();
                GetDeviceObdExFactoryBatchInfoDO getDeviceObdExFactoryBatchInfoDO = new GetDeviceObdExFactoryBatchInfoDO();
                getDeviceObdExFactoryBatchInfoDO.setFactoryUserId(sysUser.getUserId());
                getDeviceObdExFactoryBatchInfoDO.setSortRow("createTime");
                List<DeviceObdExFactoryBatchInfo> batchList = deviceObdExFactoryBatchInfoService.getAllList(getDeviceObdExFactoryBatchInfoDO);
                if(batchList!=null && batchList.size()>0){
                    batchIds = batchList.stream().map(DeviceObdExFactoryBatchInfo::getBatchId).collect(Collectors.toList());
                }else{
                    batchIds.add(0l);
                }
                getDeviceObdBaseInfoDO.setBatchIds(batchIds);
            }
        }
        getDeviceObdBaseInfoDO.setSortRow("onLineStatus");
        getDeviceObdBaseInfoDO.setSortOrder("desc");
        List<DeviceObdBaseInfo> deviceList = deviceObdBaseInfoService.getPageList(getDeviceObdBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            Map<Long,SystemDeviceModelInfo> modelMap = new HashMap<>();
            deviceList.forEach(item -> {
                GetDeviceListVO vo = EntityConversionUtil.copy(item, GetDeviceListVO.class);
                vo.setDeviceId(item.getId());
                String aerialStatus = item.getAerialStatus();
                if (aerialStatus == null || "".equals(aerialStatus)) {//无状态
                    aerialStatus = "无状态";
                } else if ("00".equals(aerialStatus)) {//正常
                    aerialStatus = "正常";
                } else if ("1".equals(aerialStatus.substring(aerialStatus.length() - 1, aerialStatus.length()))) {//短路
                    aerialStatus = "短路";
                } else if ("1".equals(aerialStatus.substring(0, 1))) {//开路
                    aerialStatus = "开路";
                } else {
                    aerialStatus = "无状态";
                }
                vo.setAerialStatus(aerialStatus);
                String factoryName = "";
                if (item.getFactoryUserId() != null && item.getFactoryUserId() > 0) {
                    UserInfo userInfo = userInfoService.getById(item.getFactoryUserId());
                    if (userInfo != null) {
                        factoryName = userInfo.getName();
                    }
                }
                String batchNo = "";
                String exDate = "";
                String modelName = "";
                if (item.getBatchId() != null && item.getBatchId() > 0) {
                    DeviceObdExFactoryBatchInfo batchInfo = deviceObdExFactoryBatchInfoService.getById(item.getBatchId());
                    if (batchInfo != null) {
                        batchNo = batchInfo.getBatchNo();
                        if (batchInfo.getExDate() != null) {
                            exDate = DateUtils.parseDateToStr(batchInfo.getExDate(), DateUtils.DATE_FORMAT_YYYY_MM_DD);
                        }
                    }
                    SystemDeviceModelInfo modelInfo = modelMap.get(item.getBatchId());
                    if(modelInfo == null){
                        if(batchInfo!=null && batchInfo.getModelId()!=null){
                            modelInfo = systemDeviceModelInfoService.getById(batchInfo.getModelId());
                            if(modelInfo!=null){
                                modelMap.put(item.getBatchId(),modelInfo);
                                modelName = modelInfo.getName();
                            }
                        }
                    }else{
                        modelName = modelInfo.getName();
                    }
                }
                vo.setBatchNo(batchNo);
                vo.setExDate(exDate);
                vo.setFactoryName(factoryName);
                vo.setModelName(modelName);
                String serviceStartTime = "";
                String serviceEndTime = "";
                String activationTime = "";
                if(item.getServiceStartTime()!=null)serviceStartTime = DateUtils.parseDateToStr(item.getServiceStartTime(),DateUtils.DATE_FORMAT_YYYY_MM_DD);
                if(item.getServiceEndTime()!=null)serviceEndTime = DateUtils.parseDateToStr(item.getServiceEndTime(),DateUtils.DATE_FORMAT_YYYY_MM_DD);
                if(item.getActivationTime()!=null)activationTime = DateUtils.parseDateToStr(item.getActivationTime(),DateUtils.DATE_FORMAT_YYYY_MM_DD);
                vo.setServiceStartTime(serviceStartTime);
                vo.setServiceEndTime(serviceEndTime);
                vo.setActivationTime(activationTime);
                String dormancy = "";
                if(item.getValue1()!=null && !"".equals(item.getValue1())){
                    if(Integer.valueOf(item.getValue1())<10)dormancy = "1";
                    else dormancy = "0";
                }
                vo.setDormancy(dormancy);
                voList.add(vo);
            });
        }
        PageInfo<DeviceObdBaseInfo> pageInfo = new PageInfo<>(deviceList);
        PageResult<List<GetDeviceListVO>> build = PageResult.<List<GetDeviceListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "OBD终端管理-查看维修终端列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "查看维修终端列表")
    @PostMapping("/getRepairDeviceList")
    public Result<PageResult<List<GetDeviceListVO>>> getRepairDeviceList(@RequestBody @Valid GetRepairDeviceListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetDeviceListVO> voList = new ArrayList<>();
        GetDeviceObdBatchRepairRecordMappingInfoDO getDeviceObdBatchRepairRecordMappingInfoDO = new GetDeviceObdBatchRepairRecordMappingInfoDO();
        getDeviceObdBatchRepairRecordMappingInfoDO.setBatchId(dto.getBatchId());
        getDeviceObdBatchRepairRecordMappingInfoDO.setSortRow("id");
        List<DeviceObdBatchRepairRecordMappingInfo> mappingList = deviceObdBatchRepairRecordMappingInfoService.getAllList(getDeviceObdBatchRepairRecordMappingInfoDO);
        List<String> dtus = new ArrayList<>();
        dtus.add("0");
        if(!CollectionUtils.isEmpty(mappingList)){
            dtus = mappingList.stream().map(DeviceObdBatchRepairRecordMappingInfo::getDtu).collect(Collectors.toList());
        }
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setPage(dto.getPage());
        getDeviceObdBaseInfoDO.setPageSize(dto.getPageSize());
        getDeviceObdBaseInfoDO.setDtus(dtus);
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        if ((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_厂家配置) && !"testadmin".equals(sysUser.getName()) && sysUser.getUserId() != null) {
            if(getDeviceObdBaseInfoDO.getFactoryUserId() == null)getDeviceObdBaseInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        //特殊处理
        if ("15210999919".equals(sysUser.getName())) {
            getDeviceObdBaseInfoDO.setFactoryUserId(null);
            getDeviceObdBaseInfoDO.setPrefix("02");
        }
        //处理可二次销售厂家的情况
        if((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 ||sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2) && sysUser.getUserId()!=null){
            UserInfo userInfo = userInfoService.getById(sysUser.getUserId());
            if (userInfo != null && userInfo.getAllowSecondSupply() == 1) {
                getDeviceObdBaseInfoDO.setFactoryUserId(null);
                List<Long> batchIds = new ArrayList<>();
                GetDeviceObdExFactoryBatchInfoDO getDeviceObdExFactoryBatchInfoDO = new GetDeviceObdExFactoryBatchInfoDO();
                getDeviceObdExFactoryBatchInfoDO.setFactoryUserId(sysUser.getUserId());
                getDeviceObdExFactoryBatchInfoDO.setSortRow("createTime");
                List<DeviceObdExFactoryBatchInfo> batchList = deviceObdExFactoryBatchInfoService.getAllList(getDeviceObdExFactoryBatchInfoDO);
                if (batchList != null && batchList.size() > 0) {
                    batchIds = batchList.stream().map(DeviceObdExFactoryBatchInfo::getBatchId).collect(Collectors.toList());
                } else {
                    batchIds.add(0l);
                }
                getDeviceObdBaseInfoDO.setBatchIds(batchIds);
            }
        }
        getDeviceObdBaseInfoDO.setSortRow("onLineStatus");
        getDeviceObdBaseInfoDO.setSortOrder("desc");
        List<DeviceObdBaseInfo> deviceList = deviceObdBaseInfoService.getPageList(getDeviceObdBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            Map<Long, SystemDeviceModelInfo> modelMap = new HashMap<>();
            deviceList.forEach(item -> {
                GetDeviceListVO vo = EntityConversionUtil.copy(item, GetDeviceListVO.class);
                vo.setDeviceId(item.getId());
                String aerialStatus = item.getAerialStatus();
                if (aerialStatus == null || "".equals(aerialStatus)) {//无状态
                    aerialStatus = "无状态";
                } else if ("00".equals(aerialStatus)) {//正常
                    aerialStatus = "正常";
                } else if ("1".equals(aerialStatus.substring(aerialStatus.length() - 1, aerialStatus.length()))) {//短路
                    aerialStatus = "短路";
                } else if ("1".equals(aerialStatus.substring(0, 1))) {//开路
                    aerialStatus = "开路";
                } else {
                    aerialStatus = "无状态";
                }
                vo.setAerialStatus(aerialStatus);
                String factoryName = "";
                if (item.getFactoryUserId() != null && item.getFactoryUserId() > 0) {
                    UserInfo userInfo = userInfoService.getById(item.getFactoryUserId());
                    if (userInfo != null) {
                        factoryName = userInfo.getName();
                    }
                }
                String batchNo = "";
                String exDate = "";
                String modelName = "";
                if (item.getBatchId() != null && item.getBatchId() > 0) {
                    DeviceObdExFactoryBatchInfo batchInfo = deviceObdExFactoryBatchInfoService.getById(item.getBatchId());
                    if (batchInfo != null) {
                        batchNo = batchInfo.getBatchNo();
                        if (batchInfo.getExDate() != null) {
                            exDate = DateUtils.parseDateToStr(batchInfo.getExDate(), DateUtils.DATE_FORMAT_YYYY_MM_DD);
                        }
                    }
                    SystemDeviceModelInfo modelInfo = modelMap.get(item.getBatchId());
                    if (modelInfo == null) {
                        if (batchInfo != null && batchInfo.getModelId() != null) {
                            modelInfo = systemDeviceModelInfoService.getById(batchInfo.getModelId());
                            if (modelInfo != null) {
                                modelMap.put(item.getBatchId(), modelInfo);
                                modelName = modelInfo.getName();
                            }
                        }
                    } else {
                        modelName = modelInfo.getName();
                    }
                }
                vo.setBatchNo(batchNo);
                vo.setExDate(exDate);
                vo.setFactoryName(factoryName);
                vo.setModelName(modelName);
                String serviceStartTime = "";
                String serviceEndTime = "";
                String activationTime = "";
                if (item.getServiceStartTime() != null)
                    serviceStartTime = DateUtils.parseDateToStr(item.getServiceStartTime(), DateUtils.DATE_FORMAT_YYYY_MM_DD);
                if (item.getServiceEndTime() != null)
                    serviceEndTime = DateUtils.parseDateToStr(item.getServiceEndTime(), DateUtils.DATE_FORMAT_YYYY_MM_DD);
                if (item.getActivationTime() != null)
                    activationTime = DateUtils.parseDateToStr(item.getActivationTime(), DateUtils.DATE_FORMAT_YYYY_MM_DD);
                vo.setServiceStartTime(serviceStartTime);
                vo.setServiceEndTime(serviceEndTime);
                vo.setActivationTime(activationTime);
                String dormancy = "";
                if (item.getValue1() != null && !"".equals(item.getValue1())) {
                    if (Integer.valueOf(item.getValue1()) < 10) dormancy = "1";
                    else dormancy = "0";
                }
                vo.setDormancy(dormancy);
                voList.add(vo);
            });
        }
        PageInfo<DeviceObdBaseInfo> pageInfo = new PageInfo<>(deviceList);
        PageResult<List<GetDeviceListVO>> build = PageResult.<List<GetDeviceListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "OBD终端管理-获取每天的激活数量数据", businessType = BusinessType.INSERT)
    @ApiOperation(value = "获取每天的激活数量数据")
    @PostMapping("/getActivationDataInDay")
    public Result<PageResult<List<GetActivationDataInDayVO>>> getActivationDataInDay(@RequestBody @Valid GetDeviceListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetActivationDataInDayVO> voList = new ArrayList<>();
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdBaseInfoDO.class);
        getDeviceObdBaseInfoDO.setHasActivation(1);
        if (dto.getCartonNo() != null && !"".equals(dto.getCartonNo())) {
            getDeviceObdBaseInfoDO.setCartonNo(null);
            getDeviceObdBaseInfoDO.setCartonNoLike(dto.getCartonNo());
        }
        if (dto.getFactoryId() != null) {
            UserInfo userInfo = userInfoService.getById(dto.getFactoryId());
            if (userInfo != null && userInfo.getAllowSecondSupply() == 1) {
                getDeviceObdBaseInfoDO.setFactoryUserId(null);
                List<Long> batchIds = new ArrayList<>();
                GetDeviceObdExFactoryBatchInfoDO getDeviceObdExFactoryBatchInfoDO = new GetDeviceObdExFactoryBatchInfoDO();
                getDeviceObdExFactoryBatchInfoDO.setFactoryUserId(dto.getFactoryId());
                getDeviceObdExFactoryBatchInfoDO.setSortRow("createTime");
                List<DeviceObdExFactoryBatchInfo> batchList = deviceObdExFactoryBatchInfoService.getAllList(getDeviceObdExFactoryBatchInfoDO);
                if (batchList != null && batchList.size() > 0) {
                    batchIds = batchList.stream().map(DeviceObdExFactoryBatchInfo::getBatchId).collect(Collectors.toList());
                } else {
                    batchIds.add(0l);
                }
                getDeviceObdBaseInfoDO.setBatchIds(batchIds);
            } else {
                getDeviceObdBaseInfoDO.setFactoryUserId(dto.getFactoryId());
            }
        }
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        if ((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 ||sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_厂家配置) && !"testadmin".equals(sysUser.getName()) && sysUser.getUserId() != null) {
            if(getDeviceObdBaseInfoDO.getFactoryUserId() == null)getDeviceObdBaseInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        //特殊处理
        if ("15210999919".equals(sysUser.getName())) {
            getDeviceObdBaseInfoDO.setFactoryUserId(null);
            getDeviceObdBaseInfoDO.setPrefix("02");
        }
        //处理可二次销售厂家的情况
        if((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2) && sysUser.getUserId()!=null){
            UserInfo userInfo = userInfoService.getById(sysUser.getUserId());
            if (userInfo != null && userInfo.getAllowSecondSupply() == 1) {
                getDeviceObdBaseInfoDO.setFactoryUserId(null);
                List<Long> batchIds = new ArrayList<>();
                GetDeviceObdExFactoryBatchInfoDO getDeviceObdExFactoryBatchInfoDO = new GetDeviceObdExFactoryBatchInfoDO();
                getDeviceObdExFactoryBatchInfoDO.setFactoryUserId(sysUser.getUserId());
                getDeviceObdExFactoryBatchInfoDO.setSortRow("createTime");
                List<DeviceObdExFactoryBatchInfo> batchList = deviceObdExFactoryBatchInfoService.getAllList(getDeviceObdExFactoryBatchInfoDO);
                if (batchList != null && batchList.size() > 0) {
                    batchIds = batchList.stream().map(DeviceObdExFactoryBatchInfo::getBatchId).collect(Collectors.toList());
                } else {
                    batchIds.add(0l);
                }
                getDeviceObdBaseInfoDO.setBatchIds(batchIds);
            }
        }
        getDeviceObdBaseInfoDO.setSortRow("day");
        getDeviceObdBaseInfoDO.setSortOrder("desc");
        List<Map<String, Object>> deviceList = deviceObdBaseInfoService.getActivationDataInDay(getDeviceObdBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            deviceList.forEach(item -> {
                GetActivationDataInDayVO vo = new GetActivationDataInDayVO();
                vo.setDay(item.get("day").toString());
                vo.setNumber(Integer.parseInt(item.get("num").toString()));
                voList.add(vo);
            });
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(deviceList);
        PageResult<List<GetActivationDataInDayVO>> build = PageResult.<List<GetActivationDataInDayVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "OBD终端管理-获取每天的在线数量数据", businessType = BusinessType.INSERT)
    @ApiOperation(value = "获取每天的在线数量数据")
    @PostMapping("/getOnLineDataInDay")
    public Result<PageResult<List<GetOnLineDataInDayVO>>> getOnLineDataInDay(@RequestBody @Valid GetDeviceListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetOnLineDataInDayVO> voList = new ArrayList<>();
        GetDeviceObdWorkDailyRecordInfoDO getDeviceObdWorkDailyRecordInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdWorkDailyRecordInfoDO.class);
        getDeviceObdWorkDailyRecordInfoDO.setSortRow("day");
        getDeviceObdWorkDailyRecordInfoDO.setSortOrder("desc");
        List<Map<String, Object>> deviceList = deviceObdWorkDailyRecordInfoService.getOnLineDataInDay(getDeviceObdWorkDailyRecordInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            deviceList.forEach(item -> {
                GetOnLineDataInDayVO vo = new GetOnLineDataInDayVO();
                vo.setDay(item.get("day").toString());
                vo.setNumber(Integer.parseInt(item.get("num").toString()));
                voList.add(vo);
            });
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(deviceList);
        PageResult<List<GetOnLineDataInDayVO>> build = PageResult.<List<GetOnLineDataInDayVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "OBD终端管理-APP终端列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "APP终端列表")
    @PostMapping("/getDeviceListInApp")
    public Result<PageResult<List<GetDeviceListVO>>> getDeviceListInApp(@RequestBody @Valid GetDeviceListInAppDTO dto) {
        SysUser sysUser = sysUserService.getByUserId(dto.getUserId());
        List<GetDeviceListVO> voList = new ArrayList<>();
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdBaseInfoDO.class);
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        if (sysUser != null) {
            if ((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_厂家配置) && !"testadmin".equals(sysUser.getName()) && sysUser.getUserId() != null) {
                getDeviceObdBaseInfoDO.setFactoryUserId(sysUser.getUserId());
            }
            //特殊处理
            if ("15210999919".equals(sysUser.getName())) {
                getDeviceObdBaseInfoDO.setFactoryUserId(null);
                getDeviceObdBaseInfoDO.setPrefix("02");
            }
        } else getDeviceObdBaseInfoDO.setFactoryUserId(dto.getUserId());
        getDeviceObdBaseInfoDO.setSortRow("onLineStatus");
        getDeviceObdBaseInfoDO.setSortOrder("desc");
        List<DeviceObdBaseInfo> deviceList = new ArrayList<>();
        if (dto.getPage() == 0) {
            getDeviceObdBaseInfoDO.setLon("111");
            deviceList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        } else {
            deviceList = deviceObdBaseInfoService.getPageList(getDeviceObdBaseInfoDO);
        }
        if (deviceList != null && deviceList.size() > 0) {
//            voList = EntityConversionUtil.copyList(deviceList,GetDeviceListVO.class);
            deviceList.forEach(item -> {
                GetDeviceListVO vo = EntityConversionUtil.copy(item, GetDeviceListVO.class);
                vo.setDeviceId(item.getId());
                voList.add(vo);
            });
        }
        PageInfo<DeviceObdBaseInfo> pageInfo = new PageInfo<>(deviceList);
        PageResult<List<GetDeviceListVO>> build = PageResult.<List<GetDeviceListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "OBD终端管理-APP终端分布", businessType = BusinessType.INSERT)
    @ApiOperation(value = "APP终端分布")
    @PostMapping("/getDistributionListInApp")
    public Result<List<GetDeviceDistributionInAppVO>> getDeviceDistributionInApp(@RequestBody @Valid GetDeviceDistributionInAppDTO dto) {
        SysUser sysUser = sysUserService.getByUserId(dto.getUserId());
        List<GetDeviceDistributionInAppVO> voList = new ArrayList<>();
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdBaseInfoDO.class);
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        if (sysUser != null) {
            if ((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_厂家配置) && !"testadmin".equals(sysUser.getName()) && sysUser.getUserId() != null) {
                getDeviceObdBaseInfoDO.setFactoryUserId(sysUser.getUserId());
            }
            //特殊处理
            if ("15210999919".equals(sysUser.getName())) {
                getDeviceObdBaseInfoDO.setFactoryUserId(null);
                getDeviceObdBaseInfoDO.setPrefix("02");
            }
        } else getDeviceObdBaseInfoDO.setFactoryUserId(dto.getUserId());
        getDeviceObdBaseInfoDO.setSortRow("onLineStatus");
        getDeviceObdBaseInfoDO.setSortOrder("desc");
        List<DeviceObdBaseInfo> deviceList = new ArrayList<>();
        getDeviceObdBaseInfoDO.setLon("111");
        deviceList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            voList = EntityConversionUtil.copyList(deviceList, GetDeviceDistributionInAppVO.class);
        }
        return Result.suc(voList);
    }

    @Log(title = "OBD终端管理- 设备维修", businessType = BusinessType.INSERT)
    @ApiOperation(value = "设备维修")
    @PostMapping("/saveRepairInfo")
    public Result<List<SaveRepairInfoVO>> saveRepairInfo(@RequestBody @Valid SaveRepairInfoDTO dto) {
        List<SaveRepairInfoVO> voList = new ArrayList<>();
        if (StringUtils.isBlank(dto.getPwd()) || !"Zhihuiobd123".equals(dto.getPwd())) {
            return Result.fail("9999", "密码不正确");
        }
        DeviceObdRepairRecordInfo recordInfo = EntityConversionUtil.copy(dto, DeviceObdRepairRecordInfo.class);
        System.out.println("===========imei :" + recordInfo.getImei());
        List<DeviceObdBaseInfo> baseList = deviceObdRepairRecordInfoService.saveRepairInfo(recordInfo);
        if (baseList != null && baseList.size() > 0) {
            voList = EntityConversionUtil.copyList(baseList, SaveRepairInfoVO.class);
        }
        return Result.suc(voList);
    }
    @Log(title = "OBD终端管理- 批量设备维修", businessType = BusinessType.INSERT)
    @ApiOperation(value = "批量设备维修")
    @PostMapping("/saveRepairInfoInBatch")
    public Result<List<SaveRepairInfoVO>> saveRepairInfoInBatch(@RequestBody @Valid SaveRepairInfoInBatchDTO dto) {
        List<SaveRepairInfoVO> voList = new ArrayList<>();
        if (StringUtils.isBlank(dto.getPwd()) || !"Zhihuiobd123".equals(dto.getPwd())) {
            return Result.fail("9999", "密码不正确");
        }
        List<List<Object>> list1 = new ArrayList<>();
        try{
            String filePath1 = "";
            if (StringUtils.isNotBlank(dto.getFileUrl()) && dto.getFileUrl().indexOf("upload") > -1) {
                int index = dto.getFileUrl().indexOf("upload");
                filePath1 = "/zhnl/ftp/" + dto.getFileUrl().substring(index, dto.getFileUrl().length());
            }

            File file1 = new File(filePath1);
            String fileName1 = filePath1.split("\\/")[filePath1.split("\\/").length-1];
            FileInputStream in1 =new FileInputStream(file1);
            list1 = ExcelUtil.getBankListByExcel(in1,fileName1);

        }catch (Exception e){
            e.printStackTrace();
        }
        if(CollectionUtils.isEmpty(list1) || CollectionUtils.isEmpty(list1)){
            return Result.fail("9999","文件为空");
        }
        List<String> strList = new ArrayList<>();
        for (int i=1;i<list1.size();i++) {
            List<Object> oList = list1.get(i);
            String str = oList.get(0).toString();
            if(strList.contains(str)){
                return Result.fail("9999",str+" - 重复设备");
            }
            strList.add(str);
        }
        if(CollectionUtils.isEmpty(strList)){
            return Result.fail("9999","文件为空");
        }
        List<DeviceObdBaseInfo> baseList = new ArrayList<>();
        List<String> sdtuList = new ArrayList<>();
        for(String s:strList){
            if(s.startsWith("86")){
                List<DeviceObdBaseInfo> tempList = deviceObdBaseInfoService.getByImei(s);
                if(CollectionUtils.isEmpty(tempList)){
                    return Result.fail("9999",s+" - 设备不存在");
                }
                if(tempList.size()>1){
                    return Result.fail("9999",s+" - 设备有多台");
                }
                DeviceObdBaseInfo baseInfo = tempList.get(0);
                if(baseInfo.getBatchId() == null || baseInfo.getBatchId() == 0){
                    return Result.fail("9999",s+" - 设备未出厂");
                }
                baseList.add(baseInfo);
                sdtuList.add(s);
            }else{
                DeviceObdRepairExFactoryBatchInfo batchInfo = deviceObdRepairExFactoryBatchInfoService.getById(dto.getBatchId());
                if(batchInfo  == null ){
                    return Result.fail("9999","批次不存在");
                }
                if(batchInfo.getExFactory() == 1){
                    return Result.fail("9999","批次已出库");
                }
                GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
                getDeviceObdBaseInfoDO.setFactoryUserId(batchInfo.getFactoryUserId());
                getDeviceObdBaseInfoDO.setDtu(s.substring(s.length()-5,s.length()));
                getDeviceObdBaseInfoDO.setSortRow("id");
                List<DeviceObdBaseInfo> tempBaseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
                if(tempBaseList==null || tempBaseList.size()==0){
                    return Result.fail("9999",s+" - 不存在");
                }else if(tempBaseList.size()>1){
                    return Result.fail("9999",s+" - 有重复记录");
                }else{
                    baseList.add(tempBaseList.get(0));
                    sdtuList.add(s);
                }
            }
        }
        if(baseList.size()>0){
            DeviceObdBatchRepairRecordInfo recordInfo = new DeviceObdBatchRepairRecordInfo();
            recordInfo.setBatchId(dto.getBatchId());
            recordInfo.setFileUrl(dto.getFileUrl());
            recordInfo.setRemark(dto.getRemark());
            deviceObdBatchRepairRecordInfoService.save(recordInfo,baseList,sdtuList);
        }
        return Result.suc(voList);
    }

    @Log(title = "OBD终端管理- 修改开关设置，GPS发送间隔时间，沃德和大田数据发送开关", businessType = BusinessType.INSERT)
    @ApiOperation(value = "修改发送数据给各平台的开关")
    @PostMapping("/updateSwitchSetting")
    public Result<Objects> updateSwitchSetting(@RequestBody @Valid UpdateSwitchSettingDTO dto) {
        DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getById(dto.getDeviceId());
        if (baseInfo == null) {
            return Result.fail("9999", "设备不存在");
        }
        if (dto.getTime() != baseInfo.getSetGps()) {//发送间隔时间
            baseInfo.setSetGps(dto.getTime());
            baseInfo.setSetGpsSwitch(1);
            baseInfo.setSetGpsStatus(1);
        }
        if (dto.getWodeSwitch() != baseInfo.getSetWode()) {//沃德数据发送开关
            baseInfo.setSetWode(dto.getWodeSwitch());
            baseInfo.setSetWodeSwitch(1);
            baseInfo.setSetWodeStatus(1);
        }
        if (dto.getDatianSwitch() != baseInfo.getSetDatian()) {//大田数据发送开送
            baseInfo.setSetDatian(dto.getDatianSwitch());
            baseInfo.setSetDatianSwitch(1);
            baseInfo.setSetDatianStatus(1);
        }
        deviceObdBaseInfoService.update(baseInfo);
        return Result.suc();
    }

    @Log(title = "OBD终端管理-定位监控", businessType = BusinessType.SELECT)
    @ApiOperation(value = "定位监控")
    @PostMapping("/getGpsMonitorList")
    public Result<PageResult<List<GetGpsMonitorListVO>>> getGpsMonitorList(@RequestBody @Valid GetGpsMonitorListDTO dto) {
        List<String> dtuList = null;
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        boolean isObdFactory = false;
        if ((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2) && !"testadmin".equals(sysUser.getName()) && sysUser.getUserId() != null) {
            isObdFactory = true;
            dtuList = new ArrayList<>();
            dtuList.add("0");
            GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
            getDeviceObdBaseInfoDO.setFactoryUserId(sysUser.getUserId());
            //特殊处理
            if ("15210999919".equals(sysUser.getName())) {
                getDeviceObdBaseInfoDO.setFactoryUserId(null);
                getDeviceObdBaseInfoDO.setPrefix("02");
            }
            getDeviceObdBaseInfoDO.setSortRow("id");
            List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
            if (baseList != null && baseList.size() > 0) {
                dtuList.addAll(baseList.stream().map(item -> item.getDtu()).collect(Collectors.toList()));
            }
        }
        //生产厂家
        if (isObdFactory) {
            DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dto.getDtu());
            if (baseInfo != null && baseInfo.getBatchId() != null && baseInfo.getBatchId() > 0) {
                DeviceObdExFactoryBatchInfo batchInfo = deviceObdExFactoryBatchInfoService.getById(baseInfo.getBatchId());
                if (batchInfo == null || batchInfo.getExFactory() == 0) {
                    throw new BusinessException(ErrorCodeEnum.DATA_NOT_FOUNT);
                }
                //查询的日期为出厂前的
                if (DateUtils.compareTwoTimeBefore(DateUtils.parseStrToDate(dto.getStartTime(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS), batchInfo.getExDate())) {
                    throw new BusinessException(ErrorCodeEnum.DATA_NOT_FOUNT);
                }
            }
        }
        List<GetGpsMonitorListVO> voList = new ArrayList<>();
        List<DeviceObdGpsInfo> gpsList = new ArrayList<>();
        if (dto.getDataType() == 1) {//正常
            GetDeviceObdGpsInfoDO getDeviceObdGpsInfoDO = new GetDeviceObdGpsInfoDO();
            getDeviceObdGpsInfoDO.setDtu(dto.getDtu());
            String tableName = "device_obd_gps_info_";
            getDeviceObdGpsInfoDO.setPage(dto.getPage());
            getDeviceObdGpsInfoDO.setPageSize(dto.getPageSize());
            getDeviceObdGpsInfoDO.setSTime(dto.getStartTime());
            getDeviceObdGpsInfoDO.setETime(dto.getEndTime());
            tableName += dto.getStartTime().split(" ")[0].replaceAll("-", "");
            getDeviceObdGpsInfoDO.setSortRow("time");
            getDeviceObdGpsInfoDO.setSortOrder("desc");
            getDeviceObdGpsInfoDO.setTableName(tableName);
            if (dtuList != null && dtuList.size() > 0) {
                getDeviceObdGpsInfoDO.setDtuList(dtuList);
            }
            gpsList = deviceObdGpsInfoService.getPageList(getDeviceObdGpsInfoDO);
        } else {//断点
            GetDeviceObdGpsInfoDO getDeviceObdGpsInfoDO = new GetDeviceObdGpsInfoDO();
            getDeviceObdGpsInfoDO.setDtu(dto.getDtu());
            String tableName = "device_obd_gps_info_";
            getDeviceObdGpsInfoDO.setPage(dto.getPage());
            getDeviceObdGpsInfoDO.setPageSize(dto.getPageSize());
            getDeviceObdGpsInfoDO.setSTime(dto.getStartTime());
            getDeviceObdGpsInfoDO.setETime(dto.getEndTime());
            tableName += dto.getStartTime().split(" ")[0].replaceAll("-", "");
            getDeviceObdGpsInfoDO.setSortRow("time");
            getDeviceObdGpsInfoDO.setSortOrder("desc");
            getDeviceObdGpsInfoDO.setTableName(tableName);
            if (dtuList != null && dtuList.size() > 0) {
                getDeviceObdGpsInfoDO.setDtuList(dtuList);
            }
            List<DeviceObdGpsInfo> tempGpsList = deviceObdGpsInfoService.getAllList(getDeviceObdGpsInfoDO);
            if (tempGpsList != null && tempGpsList.size() > 0) {
                DeviceObdGpsInfo info2 = tempGpsList.get(0);
                for (int i = 1; i < tempGpsList.size(); i++) {
                    DeviceObdGpsInfo info1 = tempGpsList.get(i);
                    Date date1 = info1.getTime();
                    Date date2 = info2.getTime();
                    long second = DateUtils.calSecond(date1, date2);
                    if (second > dto.getBreakPoint()) {
                        gpsList.add(info2);
                        gpsList.add(info1);
                    }
                    info2 = info1;
                }
            }
        }
        gpsList.forEach(item -> {
            GetGpsMonitorListVO vo = EntityConversionUtil.copy(item, GetGpsMonitorListVO.class);
            vo.setSpeed(new BigDecimal(item.getSpeed()).multiply(new BigDecimal(1.852)).setScale(2, BigDecimal.ROUND_HALF_DOWN));
            voList.add(vo);
        });
        PageInfo<DeviceObdGpsInfo> pageInfo = new PageInfo<>(gpsList);
        PageResult<List<GetGpsMonitorListVO>> build = PageResult.<List<GetGpsMonitorListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "OBD终端管理-扫描纸箱查询终端列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "扫描纸箱查询终端列表")
    @PostMapping("/getDeviceListByCarton")
    public Result<PageResult<List<GetDeviceListByCartonVO>>> getDeviceListByCarton(@RequestBody @Valid GetDeviceListByCartonDTO dto) {
        List<GetDeviceListByCartonVO> voList = new ArrayList<>();
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdBaseInfoDO.class);
        getDeviceObdBaseInfoDO.setSortRow("cartonNo");
        List<DeviceObdBaseInfo> deviceList = deviceObdBaseInfoService.getPageList(getDeviceObdBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            voList = EntityConversionUtil.copyList(deviceList, GetDeviceListByCartonVO.class);
        }
        PageInfo<DeviceObdBaseInfo> pageInfo = new PageInfo<>(deviceList);
        PageResult<List<GetDeviceListByCartonVO>> build = PageResult.<List<GetDeviceListByCartonVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "OBD终端管理-获取当前出厂的批次信息", businessType = BusinessType.SELECT)
    @ApiOperation(value = "获取当前出厂的批次信息")
    @PostMapping("/getExFactoryBatchInfo")
    public Result<GetExFactoryBatchInfoVO> getExFactoryBatchInfo() {
        GetExFactoryBatchInfoVO vo = new GetExFactoryBatchInfoVO();
        GetDeviceObdExFactoryBatchInfoDO getDeviceObdExFactoryBatchInfoDO = new GetDeviceObdExFactoryBatchInfoDO();
        getDeviceObdExFactoryBatchInfoDO.setExFactory(0);
        getDeviceObdExFactoryBatchInfoDO.setSortRow("createTime");
        List<DeviceObdExFactoryBatchInfo> list = deviceObdExFactoryBatchInfoService.getAllList(getDeviceObdExFactoryBatchInfoDO);
        if (list != null && list.size() > 0) {
            vo = EntityConversionUtil.copy(list.get(0), GetExFactoryBatchInfoVO.class);
        } else {
            return Result.fail("9999", "当前没有未出厂的批次");
        }
        return Result.suc(vo);
    }

    @Log(title = "OBD终端管理- 工厂老化扫描查询", businessType = BusinessType.INSERT)
    @ApiOperation(value = "工厂老化扫描查询")
    @PostMapping("/getDeviceInfoByScan")
    public Result<GetDeviceInfoByScanVO> getDeviceInfoByScan(@RequestBody @Valid GetDeviceInfoByScanDTO dto) {
        GetDeviceInfoByScanVO vo = new GetDeviceInfoByScanVO();
        String prefix = dto.getPrefix();
        if (StringUtils.isBlank(dto.getPrefix())) {
            return Result.fail("9999", "前缀不能为空");
        }
        String sdtu = dto.getSdtu();
        if (StringUtils.isBlank(dto.getSdtu())) {
            return Result.fail("9999", "扫描编号不能为空");
        }
        DeviceObdBaseInfo baseInfo = null;
        if (sdtu.startsWith("86")) {
            List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getByImei(dto.getSdtu());
            if (baseList != null && baseList.size() > 0) {
                if (baseList.size() == 1) baseInfo = baseList.get(0);
                else if (baseList.size() > 1) {
                    vo.setStatus(0);
                    vo.setRemark("IMEI有重复设备");
                    return Result.suc(vo);
                }
            }
        } else {
            String dtu = "";
            if (sdtu.length() > 5) dtu = prefix + sdtu.substring(sdtu.length() - 5, sdtu.length());
            baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
        }
        if (baseInfo == null) {
            vo.setStatus(0);
            vo.setRemark("设备不存在");
            return Result.suc(vo);
        }
        GetDeviceInfoByScanDeviceVO deviceInfo = EntityConversionUtil.copy(baseInfo, GetDeviceInfoByScanDeviceVO.class);
        vo.setDeviceInfo(deviceInfo);
        if (baseInfo.getHasPass() == 0) {
            vo.setStatus(0);
            vo.setRemark("老化不合格");
            return Result.suc(vo);
        }
        if (baseInfo.getCjzt() == 0 && baseInfo.getDtu().indexOf("02al9900") != -1 && baseInfo.getDtu().indexOf("02ak9900") != -1) {
            vo.setStatus(0);
            vo.setRemark("拆机状态未变动");
            return Result.suc(vo);
        }
        if (baseInfo.getFdjzs() == null || Integer.valueOf(baseInfo.getFdjzs()) == 0) {
            vo.setStatus(0);
            vo.setRemark("没有工况");
            return Result.suc(vo);
        }
        vo.setStatus(1);
        vo.setRemark("合格");
        return Result.suc(vo);
    }

    @Log(title = "OBD终端管理-验证纸箱号是否能用", businessType = BusinessType.SELECT)
    @ApiOperation(value = "验证纸箱号是否能用")
    @PostMapping("/checkCartonNo")
    public Result<Objects> checkCartonNo(@RequestBody @Valid CheckCartonNoDTO dto) {
        if (StringUtils.isBlank(dto.getCartonNo())) {
            return Result.fail("9999", "纸箱号为空");
        }
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setCartonNo(dto.getCartonNo());
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (baseList != null && baseList.size() > 0) {
            return Result.fail("9999", "该纸箱号已经使用过");
        }
        return Result.suc();
    }

    @Log(title = "OBD终端管理-设备出库前扫描", businessType = BusinessType.SELECT)
    @ApiOperation(value = "设备出库前扫描")
    @PostMapping("/scanBeforeExFactory")
    public Result<ScanBeforeExFactoryVO> scanBeforeExFactory(@RequestBody @Valid ScanBeforeExFactoryDTO dto) {
        ScanBeforeExFactoryVO vo = new ScanBeforeExFactoryVO();
        String dtu = "";
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            vo.setStatus(0);
            vo.setMsg("没有批次");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        DeviceObdExFactoryBatchInfo batchInfo = deviceObdExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            vo.setStatus(0);
            vo.setMsg("批次不存在");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (batchInfo.getExFactory() == 1) {
            vo.setStatus(0);
            vo.setMsg("该批次已出厂");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (StringUtils.isBlank(dto.getPrefix())) {
            vo.setStatus(0);
            vo.setMsg("前缀不能为空");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (StringUtils.isBlank(dto.getSdtu())) {
            vo.setStatus(0);
            vo.setMsg("设备号不能为空");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        String sdtu = dto.getSdtu();
        DeviceObdBaseInfo baseInfo = null;
        if (sdtu.startsWith("86")) {
            List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getByImei(dto.getSdtu());
            if (baseList != null && baseList.size() > 0) {
                if (baseList.size() == 1) {
                    baseInfo = baseList.get(0);
                    dtu = baseInfo.getDtu();
                } else if (baseList.size() > 1) {
                    vo.setStatus(0);
                    vo.setMsg("IMEI有重复设备");
                    vo.setSdtu(dto.getSdtu());
                    vo.setDtus(dto.getDtus());
                    vo.setRepeats(dto.getRepeats());
                    return Result.suc(vo);
                }
            }
        } else {
            if (sdtu.length() > 5) {
                String[] prefixStr = dto.getPrefix().split(";");
                for (String p : prefixStr) {
                    if ("".equals(p)) continue;
                    dtu = p + sdtu.substring(sdtu.length() - 5, sdtu.length());
                    baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
                    if (baseInfo != null) {
                        break;
                    }
                }
            }
            /*if (sdtu.length() > 5) dtu = dto.getPrefix() + sdtu.substring(sdtu.length() - 5, sdtu.length());
            if (StringUtils.isBlank(dtu)) {
                vo.setStatus(0);
                vo.setMsg("设备号错误");
                vo.setSdtu(dto.getSdtu());
                vo.setDtus(dto.getDtus());
                vo.setRepeats(dto.getRepeats());
                return Result.suc(vo);
            }
            baseInfo = deviceObdBaseInfoService.getByDtu(dtu);*/
        }
        if (baseInfo == null) {
            vo.setStatus(0);
            vo.setMsg("设备不存在");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (StringUtils.isNotBlank(dto.getVersion())) {
            if (!baseInfo.getCurVersion().equals(dto.getVersion())) {
                vo.setStatus(0);
                vo.setMsg("该设备未升级");
                vo.setSdtu(dto.getSdtu());
                vo.setDtus(dto.getDtus());
                vo.setRepeats(dto.getRepeats());
                return Result.suc(vo);
            }
        }

        if (baseInfo.getBatchId() != null && baseInfo.getBatchId() != 0) {
            vo.setStatus(0);
            vo.setMsg("该设备已出库");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setImei(baseInfo.getImei());
        getDeviceObdBaseInfoDO.setSim(baseInfo.getSim());
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (baseList.size() > 1) {
            vo.setStatus(0);
            vo.setMsg("IMEI和SIM有重复");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (baseInfo.getHasPass() == 0) {
            vo.setStatus(0);
            vo.setMsg("合盖前老化不合格");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (baseInfo.getHasPass2() == null || baseInfo.getHasPass2() == 0) {
            vo.setStatus(0);
            vo.setMsg("合盖后老化不合格");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        String dtus = dto.getDtus();
        String repeats = dto.getRepeats();
        int status = 1;
        String msg = "合格";
        if (StringUtils.isBlank(dtus)) {
            dtus = dtu;
        } else {
            if (dtus.indexOf(dtu) != -1) {//有重复设备
                status = 0;
                msg = "有重复设备";
                if (StringUtils.isBlank(repeats)) {
                    repeats = dtu;
                } else {
                    if (repeats.indexOf(dtu) == -1) repeats = repeats + ";" + dtu;
                }
            } else {
                dtus = dtus + ";" + dtu;
            }
        }
        ScanBeforeExFactoryDeviceVO deviceInfo = EntityConversionUtil.copy(baseInfo, ScanBeforeExFactoryDeviceVO.class);
        if (baseInfo.getOnLineStatus() == 0) {//离线
            deviceInfo.setBlackout(1);
        } else deviceInfo.setBlackout(0);
        deviceInfo.setSdtu(dto.getSdtu());
        vo.setStatus(status);
        vo.setMsg(msg);
        vo.setSdtu(dto.getSdtu());
        vo.setRepeats(repeats);
        vo.setDtus(dtus);
        vo.setDeviceInfo(deviceInfo);
        return Result.suc(vo);
    }

    @Log(title = "OBD终端管理-维修设备出库前扫描", businessType = BusinessType.SELECT)
    @ApiOperation(value = "维修设备出库前扫描")
    @PostMapping("/scanBeforeExFactoryInRepairDevice")
    public Result<ScanBeforeExFactoryVO> scanBeforeExFactoryInRepairDevice(@RequestBody @Valid ScanBeforeExFactoryDTO dto) {
        ScanBeforeExFactoryVO vo = new ScanBeforeExFactoryVO();
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            vo.setStatus(0);
            vo.setMsg("没有批次");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        DeviceObdRepairExFactoryBatchInfo batchInfo = deviceObdRepairExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            vo.setStatus(0);
            vo.setMsg("批次不存在");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (batchInfo.getExFactory() == 1) {
            vo.setStatus(0);
            vo.setMsg("该批次已出厂");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }

        DeviceObdBatchRepairRecordMappingInfo mappingInfo = deviceObdBatchRepairRecordMappingInfoService.getByBatchIdAndSdtu(dto.getBatchId(),dto.getSdtu());
        if(mappingInfo == null){
            vo.setStatus(0);
            vo.setMsg("设备不在当前批次中");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        /*if (StringUtils.isBlank(dto.getPrefix())) {
            vo.setStatus(0);
            vo.setMsg("前缀不能为空");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }*/
        if (StringUtils.isBlank(dto.getSdtu())) {
            vo.setStatus(0);
            vo.setMsg("设备号不能为空");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        String sdtu = dto.getSdtu();
        String dtu = mappingInfo.getDtu();
        DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
        if(baseInfo == null){
            vo.setStatus(0);
            vo.setMsg("设备不存在");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        /*DeviceObdBaseInfo baseInfo = null;
        if (sdtu.startsWith("86")) {
            List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getByImei(dto.getSdtu());
            if (baseList != null && baseList.size() > 0) {
                if (baseList.size() == 1) {
                    baseInfo = baseList.get(0);
                    dtu = baseInfo.getDtu();
                } else if (baseList.size() > 1) {
                    vo.setStatus(0);
                    vo.setMsg("IMEI有重复设备");
                    vo.setSdtu(dto.getSdtu());
                    vo.setDtus(dto.getDtus());
                    vo.setRepeats(dto.getRepeats());
                    return Result.suc(vo);
                }
            }
        } else {
            if (sdtu.length() > 5) {
                String[] prefixStr = dto.getPrefix().split(";");
                for (String p : prefixStr) {
                    if ("".equals(p)) continue;
                    dtu = p + sdtu.substring(sdtu.length() - 5, sdtu.length());
                    baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
                    if (baseInfo != null) {
                        break;
                    }
                }
            }
            *//*if (sdtu.length() > 5) dtu = dto.getPrefix() + sdtu.substring(sdtu.length() - 5, sdtu.length());
            if (StringUtils.isBlank(dtu)) {
                vo.setStatus(0);
                vo.setMsg("设备号错误");
                vo.setSdtu(dto.getSdtu());
                vo.setDtus(dto.getDtus());
                vo.setRepeats(dto.getRepeats());
                return Result.suc(vo);
            }
            baseInfo = deviceObdBaseInfoService.getByDtu(dtu);*//*
        }*/
        if (StringUtils.isNotBlank(dto.getVersion())) {
            if (!baseInfo.getCurVersion().equals(dto.getVersion())) {
                vo.setStatus(0);
                vo.setMsg("该设备未升级");
                vo.setSdtu(dto.getSdtu());
                vo.setDtus(dto.getDtus());
                vo.setRepeats(dto.getRepeats());
                return Result.suc(vo);
            }
        }

        /*if (baseInfo.getBatchId() != null && baseInfo.getBatchId() != 0) {
            vo.setStatus(0);
            vo.setMsg("该设备已出库");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }*/
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setImei(baseInfo.getImei());
        getDeviceObdBaseInfoDO.setSim(baseInfo.getSim());
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (baseList.size() > 1) {
            vo.setStatus(0);
            vo.setMsg("IMEI和SIM有重复");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (baseInfo.getHasPass() == 0) {
            vo.setStatus(0);
            vo.setMsg("合盖前老化不合格");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (baseInfo.getHasPass2() == null || baseInfo.getHasPass2() == 0) {
            vo.setStatus(0);
            vo.setMsg("合盖后老化不合格");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        String dtus = dto.getDtus();
        String repeats = dto.getRepeats();
        int status = 1;
        String msg = "合格";
        if (StringUtils.isBlank(dtus)) {
            dtus = dtu;
        } else {
            if (dtus.indexOf(dtu) != -1) {//有重复设备
                status = 0;
                msg = "有重复设备";
                if (StringUtils.isBlank(repeats)) {
                    repeats = dtu;
                } else {
                    if (repeats.indexOf(dtu) == -1) repeats = repeats + ";" + dtu;
                }
            } else {
                dtus = dtus + ";" + dtu;
            }
        }
        ScanBeforeExFactoryDeviceVO deviceInfo = EntityConversionUtil.copy(baseInfo, ScanBeforeExFactoryDeviceVO.class);
        if (baseInfo.getOnLineStatus() == 0) {//离线
            deviceInfo.setBlackout(1);
        } else deviceInfo.setBlackout(0);
        deviceInfo.setSdtu(dto.getSdtu());
        vo.setStatus(status);
        vo.setMsg(msg);
        vo.setSdtu(dto.getSdtu());
        vo.setRepeats(repeats);
        vo.setDtus(dtus);
        vo.setDeviceInfo(deviceInfo);
        return Result.suc(vo);
    }

    @Log(title = "OBD终端管理-扫描设备提交出厂", businessType = BusinessType.INSERT)
    @ApiOperation(value = "扫描设备提交出厂")
    @PostMapping("/submitDeviceExFactory")
    public Result<Objects> submitDeviceExFactory(@RequestBody @Valid SubmitDeviceExFactoryDTO dto) {
        if (StringUtils.isBlank(dto.getDtus())) {
            return Result.fail("9999", "设备号为空");
        }
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            return Result.fail("9999", "批次ID为空");
        }
        if (StringUtils.isBlank(dto.getCartonNo())) {
            return Result.fail("9999", "纸箱号为空");
        }
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setCartonNo(dto.getCartonNo());
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (baseList != null && baseList.size() > 0) {
            return Result.fail("9999", "该纸箱号已经用过");
        }
        DeviceObdExFactoryBatchInfo batchInfo = deviceObdExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            return Result.fail("9999", "批次不存在");
        }
        String[] dtuStr = dto.getDtus().split(";");
        for (String dtu : dtuStr) {
            DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
            baseInfo.setBatchId(Long.valueOf(batchInfo.getBatchId()));
            baseInfo.setFactoryUserId(batchInfo.getFactoryUserId());
            baseInfo.setCartonNo(dto.getCartonNo());
            baseInfo.setSetGps(batchInfo.getSendTime());
            baseInfo.setSetGpsSwitch(1);
            baseInfo.setSetGpsStatus(1);
            deviceObdBaseInfoService.update(baseInfo);
        }
        DeviceObdExFactoryScanRecordInfo recordInfo = new DeviceObdExFactoryScanRecordInfo();
        recordInfo.setBatchId(batchInfo.getBatchId());
        recordInfo.setCartonNo(dto.getCartonNo());
        recordInfo.setPrefix(dto.getPrefix());
        recordInfo.setPassDtus(dto.getDtus());
        recordInfo.setNoPassDtus(dto.getNoPassDtus());
        deviceObdExFactoryScanRecordInfoService.save(recordInfo);
        return Result.suc();
    }


    @Log(title = "OBD终端管理-扫描维修设备提交出厂", businessType = BusinessType.INSERT)
    @ApiOperation(value = "扫描维修设备提交出厂")
    @PostMapping("/submitRepairDeviceExFactory")
    public Result<Objects> submitRepairDeviceExFactory(@RequestBody @Valid SubmitDeviceExFactoryDTO dto) {
        if (StringUtils.isBlank(dto.getDtus())) {
            return Result.fail("9999", "设备号为空");
        }
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            return Result.fail("9999", "批次ID为空");
        }
        if (StringUtils.isBlank(dto.getCartonNo())) {
            return Result.fail("9999", "纸箱号为空");
        }
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setCartonNo(dto.getCartonNo());
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (baseList != null && baseList.size() > 0) {
            return Result.fail("9999", "该纸箱号已经用过");
        }
        GetDeviceObdBatchRepairRecordMappingInfoDO getDeviceObdBatchRepairRecordMappingInfoDO = new GetDeviceObdBatchRepairRecordMappingInfoDO();
        getDeviceObdBatchRepairRecordMappingInfoDO.setCartonNo(dto.getCartonNo());
        getDeviceObdBatchRepairRecordMappingInfoDO.setSortRow("id");
        List<DeviceObdBatchRepairRecordMappingInfo> mappingList = deviceObdBatchRepairRecordMappingInfoService.getAllList(getDeviceObdBatchRepairRecordMappingInfoDO);
        if(mappingList!=null && mappingList.size()>0){
            return Result.fail("9999", "该纸箱号已经用过");
        }
        DeviceObdRepairExFactoryBatchInfo batchInfo = deviceObdRepairExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            return Result.fail("9999", "批次不存在");
        }
        getDeviceObdBatchRepairRecordMappingInfoDO.setCartonNo(null);
        getDeviceObdBatchRepairRecordMappingInfoDO.setBatchId(dto.getBatchId());
        mappingList = deviceObdBatchRepairRecordMappingInfoService.getAllList(getDeviceObdBatchRepairRecordMappingInfoDO);
        if(mappingList!=null && mappingList.size()>0){
//            String[] dtuStr = dto.getDtus().split(";");
            List<DeviceObdBatchRepairRecordMappingInfo> mappingInfoList = new ArrayList<>();
            for (DeviceObdBatchRepairRecordMappingInfo mappingInfo : mappingList) {
                mappingInfo.setCartonNo(dto.getCartonNo());
                mappingInfoList.add(mappingInfo);
            }
            deviceObdBatchRepairRecordMappingInfoService.updateList(mappingInfoList);
        }

        DeviceObdExFactoryScanRecordInfo recordInfo = new DeviceObdExFactoryScanRecordInfo();
        recordInfo.setBatchId(batchInfo.getBatchId());
        recordInfo.setCartonNo(dto.getCartonNo());
        recordInfo.setPrefix(dto.getPrefix());
        recordInfo.setPassDtus(dto.getDtus());
        recordInfo.setNoPassDtus(dto.getNoPassDtus());
        deviceObdExFactoryScanRecordInfoService.save(recordInfo);
        return Result.suc();
    }


    @Log(title = "OBD终端管理-维修出厂批次信息", businessType = BusinessType.SELECT)
    @ApiOperation(value = "维修出厂批次信息")
    @PostMapping("/getRepairBatchList")
    public Result<PageResult<List<GetRepairBatchListVO>>> getRepairBatchList(@RequestBody @Valid GetRepairBatchListDTO dto) {
        List<GetRepairBatchListVO> voList = new ArrayList<>();
        GetDeviceObdRepairExFactoryBatchInfoDO getDeviceObdRepairExFactoryBatchInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdRepairExFactoryBatchInfoDO.class);
        getDeviceObdRepairExFactoryBatchInfoDO.setSortRow("createTime");
        getDeviceObdRepairExFactoryBatchInfoDO.setExFactory(dto.getExFactory());
        List<DeviceObdRepairExFactoryBatchInfo> batchList = deviceObdRepairExFactoryBatchInfoService.getPageList(getDeviceObdRepairExFactoryBatchInfoDO);
        if (batchList != null && batchList.size() > 0) {
            for(DeviceObdRepairExFactoryBatchInfo item:batchList){
                GetRepairBatchListVO vo = EntityConversionUtil.copy(item, GetRepairBatchListVO.class);
                long deviceNum = 0;
                GetDeviceObdBatchRepairRecordMappingInfoDO getDeviceObdBatchRepairRecordMappingInfoDO = new GetDeviceObdBatchRepairRecordMappingInfoDO();
                getDeviceObdBatchRepairRecordMappingInfoDO.setBatchId(item.getBatchId());
                getDeviceObdBatchRepairRecordMappingInfoDO.setSortRow("id");
                List<DeviceObdBatchRepairRecordMappingInfo> mappingInfoList = deviceObdBatchRepairRecordMappingInfoService.getAllList(getDeviceObdBatchRepairRecordMappingInfoDO);
                if(mappingInfoList!=null && mappingInfoList.size()>0){
                    for(DeviceObdBatchRepairRecordMappingInfo mappingInfo : mappingInfoList){
                        if(StringUtils.isNotBlank(mappingInfo.getCartonNo()))deviceNum++;
                    }
                }
                vo.setDeviceNum(deviceNum);
                long factoryId = 0;
                String factoryName = "智慧农林";
                if (item.getFactoryUserId() != null && item.getFactoryUserId() > 0) {
                    factoryId = item.getFactoryUserId();
                    factoryName = item.getFactoryName();
                }
                vo.setFactoryId(factoryId);
                vo.setFactoryName(factoryName);
                /*int total = 0;
                int noActivation = 0;
                GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
                getDeviceObdBaseInfoDO.setBatchId(item.getBatchId());
                getDeviceObdBaseInfoDO.setSortRow("id");
                List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
                if (baseList != null && baseList.size() > 0) {
                    total = baseList.size();
                    for (DeviceObdBaseInfo info : baseList) {
                        if (info.getHasActivation() != null && info.getHasActivation() == 1 && (info.getFactoryUserId() == null || info.getFactoryUserId() == 0)) {
                            noActivation++;
                        }
                    }
                }
                vo.setTotal(total);
                vo.setHasActivation(noActivation);*/
                voList.add(vo);
            }
        }
        PageInfo<DeviceObdRepairExFactoryBatchInfo> pageInfo = new PageInfo<>(batchList);
        PageResult<List<GetRepairBatchListVO>> build = PageResult.<List<GetRepairBatchListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "OBD终端管理-出厂批次信息", businessType = BusinessType.SELECT)
    @ApiOperation(value = "出厂批次信息")
    @PostMapping("/getBatchList")
    public Result<PageResult<List<GetBatchListVO>>> getBatchList(@RequestBody @Valid GetBatchListDTO dto) {
        List<GetBatchListVO> voList = new ArrayList<>();
        GetDeviceObdExFactoryBatchInfoDO getDeviceObdExFactoryBatchInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdExFactoryBatchInfoDO.class);
        getDeviceObdExFactoryBatchInfoDO.setSortRow("createTime");
        getDeviceObdExFactoryBatchInfoDO.setExFactory(dto.getExFactory());
        List<DeviceObdExFactoryBatchInfo> batchList = deviceObdExFactoryBatchInfoService.getPageList(getDeviceObdExFactoryBatchInfoDO);
        if (batchList != null && batchList.size() > 0) {
            List<Long> domainIdList = new ArrayList<>();
            List<Long> modelIdList = new ArrayList<>();
            for (DeviceObdExFactoryBatchInfo info : batchList) {
                if (info.getDomainId() != null && info.getDomainId() != 0) domainIdList.add(info.getDomainId());
                if (info.getModelId() != null && info.getModelId() != 0) modelIdList.add(info.getModelId());
            }
            Map<Long, SystemDomainInfo> domainMap = new HashMap<>();
            if (domainIdList.size() > 0) {
                GetSystemDomainInfoDO getSystemDomainInfoDO = new GetSystemDomainInfoDO();
                getSystemDomainInfoDO.setIdList(domainIdList);
                getSystemDomainInfoDO.setSortRow("createTime");
                List<SystemDomainInfo> domainList = systemDomainInfoService.getAllList(getSystemDomainInfoDO);
                if (domainList != null && domainList.size() > 0) {
                    domainMap = domainList.stream().collect(Collectors.toMap(SystemDomainInfo::getId, Function.identity()));
                }
            }
            Map<Long, SystemDeviceModelInfo> modelMap = new HashMap<>();
            if (modelIdList.size() > 0) {
                GetSystemDeviceModelInfoDO getSystemDeviceModelInfoDO = new GetSystemDeviceModelInfoDO();
                getSystemDeviceModelInfoDO.setSortRow("createTime");
                getSystemDeviceModelInfoDO.setIdList(modelIdList);
                List<SystemDeviceModelInfo> modelList = systemDeviceModelInfoService.getPageList(getSystemDeviceModelInfoDO);
                if (modelList != null && modelList.size() > 0) {
                    modelMap = modelList.stream().collect(Collectors.toMap(SystemDeviceModelInfo::getId, Function.identity()));
                }
            }
            for (DeviceObdExFactoryBatchInfo item : batchList) {
                GetBatchListVO vo = EntityConversionUtil.copy(item, GetBatchListVO.class);
                vo.setDeviceNum(deviceObdBaseInfoService.countByBatchId(item.getBatchId()));
                long factoryId = 0;
                int allowSecondSupply = 0;//该关联的生产厂商是否允许二次供货
                String factoryName = "智慧农林";
                if (item.getFactoryUserId() != null && item.getFactoryUserId() > 0) {
                    UserInfo userInfo = userInfoService.getById(item.getFactoryUserId());
                    if (userInfo != null) allowSecondSupply = userInfo.getAllowSecondSupply();
                    factoryId = item.getFactoryUserId();
                    factoryName = item.getFactoryName();
                }
                vo.setAllowSecondSupply(allowSecondSupply);
                vo.setFactoryId(factoryId);
                vo.setFactoryName(factoryName);
                if (item.getDomainId() != null && item.getDomainId() != 0 && !domainMap.isEmpty() && domainMap.get(item.getDomainId()) != null) {
                    vo.setDomainId(item.getDomainId());
                    SystemDomainInfo domainInfo = domainMap.get(item.getDomainId());
                    vo.setDomainInfo(domainInfo.getDomain() + ":" + domainInfo.getPort());
                }

                if (item.getModelId() != null && item.getModelId() != 0 && !modelMap.isEmpty() && modelMap.get(item.getModelId()) != null) {
                    vo.setModelId(item.getModelId());
                    vo.setModelName(modelMap.get(item.getModelId()).getName());
                }
                int total = 0;
                int noActivation = 0;
                GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
                getDeviceObdBaseInfoDO.setBatchId(item.getBatchId());
                getDeviceObdBaseInfoDO.setSortRow("id");
                List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
                if (baseList != null && baseList.size() > 0) {
                    total = baseList.size();
                    for (DeviceObdBaseInfo info : baseList) {
                        if (info.getHasActivation() != null && info.getHasActivation() == 1 && (info.getFactoryUserId() == null || info.getFactoryUserId() == 0)) {
                            noActivation++;
                        }
                    }
                }
                vo.setTotal(total);
                vo.setHasActivation(noActivation);
                voList.add(vo);
            }
        }
        PageInfo<DeviceObdExFactoryBatchInfo> pageInfo = new PageInfo<>(batchList);
        PageResult<List<GetBatchListVO>> build = PageResult.<List<GetBatchListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "OBD终端管理-新增修改出厂批次信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增修改出厂批次信息")
    @PostMapping("/saveBatchInfo")
    public Result<Objects> saveBatchInfo(@RequestBody @Valid SaveBatchInfoDTO dto) {
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            /*GetDeviceObdExFactoryBatchInfoDO getDeviceObdExFactoryBatchInfoDO = new GetDeviceObdExFactoryBatchInfoDO();
            getDeviceObdExFactoryBatchInfoDO.setExFactory(0);
            getDeviceObdExFactoryBatchInfoDO.setSortRow("createTime");
            List<DeviceObdExFactoryBatchInfo> batchList = deviceObdExFactoryBatchInfoService.getPageList(getDeviceObdExFactoryBatchInfoDO);
            if(batchList!=null && batchList.size()>0){
                return Result.fail("9999","有未出厂的批次，不能新增");
            }*/
            DeviceObdExFactoryBatchInfo batchInfo = EntityConversionUtil.copy(dto, DeviceObdExFactoryBatchInfo.class);
            if (batchInfo.getSendTime() == null || batchInfo.getSendTime() == 0) batchInfo.setSendTime(5);
            if (batchInfo.getServiceYear() == null || batchInfo.getServiceYear() == 0) batchInfo.setServiceYear(2);
            batchInfo.setFactoryUserId(dto.getFactoryId());
            UserInfo userInfo = userInfoService.getById(dto.getFactoryId());
            if (userInfo != null)
                batchInfo.setFactoryName(userInfo.getName());
            batchInfo.setExFactory(0);
            deviceObdExFactoryBatchInfoService.save(batchInfo);
            return Result.suc();
        } else {
            DeviceObdExFactoryBatchInfo batchInfo = deviceObdExFactoryBatchInfoService.getById(dto.getBatchId());
            if (batchInfo == null) {
                return Result.fail("9999", "批次不存在");
            }
            if (batchInfo.getExFactory() == 1) {
                return Result.fail("9999", "该批次已经出厂，不能修改");
            }
            batchInfo = EntityConversionUtil.copy(dto, DeviceObdExFactoryBatchInfo.class);
            if (batchInfo.getSendTime() == null || batchInfo.getSendTime() == 0) batchInfo.setSendTime(5);
            if (batchInfo.getServiceYear() == null || batchInfo.getServiceYear() == 0) batchInfo.setServiceYear(2);
            batchInfo.setFactoryUserId(dto.getFactoryId());
            UserInfo userInfo = userInfoService.getById(dto.getFactoryId());
            if (userInfo != null)
                batchInfo.setFactoryName(userInfo.getName());
            deviceObdExFactoryBatchInfoService.update(batchInfo);
            return Result.suc();
        }
    }

    @Log(title = "OBD终端管理-新增修改维修出厂批次信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增修改维修出厂批次信息")
    @PostMapping("/saveRepairBatchInfo")
    public Result<Objects> saveRepairBatchInfo(@RequestBody @Valid SaveRepairBatchInfoDTO dto) {
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            DeviceObdRepairExFactoryBatchInfo batchInfo = EntityConversionUtil.copy(dto, DeviceObdRepairExFactoryBatchInfo.class);
            if (batchInfo.getServiceYear() == null ) batchInfo.setServiceYear(0);
            batchInfo.setFactoryUserId(dto.getFactoryId());
            UserInfo userInfo = userInfoService.getById(dto.getFactoryId());
            if (userInfo != null)
                batchInfo.setFactoryName(userInfo.getName());
            batchInfo.setExFactory(0);
            deviceObdRepairExFactoryBatchInfoService.save(batchInfo);
            return Result.suc();
        } else {
            DeviceObdRepairExFactoryBatchInfo batchInfo = deviceObdRepairExFactoryBatchInfoService.getById(dto.getBatchId());
            if (batchInfo == null) {
                return Result.fail("9999", "批次不存在");
            }
            if (batchInfo.getExFactory() == 1) {
                return Result.fail("9999", "该批次已经出厂，不能修改");
            }
            batchInfo = EntityConversionUtil.copy(dto, DeviceObdRepairExFactoryBatchInfo.class);
            if (batchInfo.getServiceYear() == null || batchInfo.getServiceYear() == 0) batchInfo.setServiceYear(2);
            batchInfo.setFactoryUserId(dto.getFactoryId());
            UserInfo userInfo = userInfoService.getById(dto.getFactoryId());
            if (userInfo != null)
                batchInfo.setFactoryName(userInfo.getName());
            deviceObdRepairExFactoryBatchInfoService.update(batchInfo);
            return Result.suc();
        }
    }

    @Log(title = "OBD终端管理-设备批次提交出库", businessType = BusinessType.INSERT)
    @ApiOperation(value = "设备批次提交出库")
    @PostMapping("/submitExFactory")
    public Result<Objects> submitExFactory(@RequestBody @Valid SubmitExFactoryDTO dto) {
        DeviceObdExFactoryBatchInfo batchInfo = deviceObdExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            return Result.fail("9999", "批次不存在");
        }
        if (batchInfo.getExFactory() == 1) {
            return Result.fail("9999", "该批次已经出库，不能重复出库");
        }
        batchInfo.setExFactory(1);
        batchInfo.setExDate(new Date());
        int num = deviceObdExFactoryBatchInfoService.updateExFactory(batchInfo);
        if (num == 0) return Result.fail("9999", "出库失败");
        return Result.suc();
    }

    @Log(title = "OBD终端管理-维修设备批次提交出库", businessType = BusinessType.INSERT)
    @ApiOperation(value = "维修设备批次提交出库")
    @PostMapping("/submitRepairExFactory")
    public Result<Objects> submitRepairExFactory(@RequestBody @Valid SubmitRepairExFactoryDTO dto) {
        DeviceObdRepairExFactoryBatchInfo batchInfo = deviceObdRepairExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            return Result.fail("9999", "批次不存在");
        }
        if (batchInfo.getExFactory() == 1) {
            return Result.fail("9999", "该批次已经出库，不能重复出库");
        }
        batchInfo.setExFactory(1);
        batchInfo.setExDate(new Date());
        int num = deviceObdRepairExFactoryBatchInfoService.updateExFactory(batchInfo);
        if (num == 0) return Result.fail("9999", "出库失败");
        return Result.suc();
    }


    @Log(title = "OBD终端管理 - 按批次导出设备信息", businessType = BusinessType.EXPORT, isSaveResponseData = false)
    @ApiOperation(value = "按批次导出设备信息")
    @PostMapping(value = "/exportDeviceListByBatch")
    public void exportDeviceListByBatch(@RequestBody @Valid ExportDeviceListByBatchDTO dto, HttpServletResponse response) throws BusinessException {
        List<ExportDeviceListByBatchVO> voList = new ArrayList<>();
        DeviceObdExFactoryBatchInfo batchInfo = deviceObdExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) return;
        String factoryName = batchInfo.getFactoryName();
//        String model = "TJ20-2";
        String model = "";
        if (batchInfo.getModelId() != null && batchInfo.getModelId() != 0) {
            SystemDeviceModelInfo modelInfo = systemDeviceModelInfoService.getById(batchInfo.getModelId());
            if (modelInfo != null) model = modelInfo.getName();
        }
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setBatchId(dto.getBatchId());
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (baseList != null && baseList.size() > 0) {
            System.out.println("====baseList :" + baseList.size());
            for (DeviceObdBaseInfo item : baseList) {
                ExportDeviceListByBatchVO vo = new ExportDeviceListByBatchVO();
                vo.setDtuType("4G");//终端类型
                String dtu = item.getDtu();
                if (dtu.length() > 5) {
                    if ("道依茨法尔".equals(factoryName)) {//道依茨法尔
                        dtu = "NJY211023091" + dtu.substring(dtu.length() - 5, dtu.length());
                    } else if ("沃得".equals(factoryName)) {
                        dtu = "5600109" + dtu.substring(dtu.length() - 5, dtu.length());
                    }
                }
                vo.setDtu(dtu);//终端编号
                /*String model = "TJ20-2";
                if("道依茨法尔".equals(factoryName) || "沃得".equals(factoryName)){
                    model = "00109";
                }*/
                vo.setModel(model);//终端型号
                vo.setCommu("");//通信协议
                vo.setSim(item.getSim());//sim卡号
                //到期时间
//                vo.setEndTime(DateUtils.parseDateToStr(DateUtils.addDate(new Date(), 2, 0, 0, 0, 0, 0, 0), DateUtils.DATE_FORMAT_YYYY_MM_DD));
                String simFactory = "";//SIM卡供應商和批次
                SimInfo simInfo = simInfoService.getByImei(item.getSim());
                if (simInfo != null) {
                    simFactory = simInfo.getSupplier() + "-" + simInfo.getBatch();
                }
//                vo.setSimFactory(simFactory);
                //到期時間
                /*String endTime = "";
                if(item.getServiceEndTime()!=null){
                    endTime = DateUtils.parseDateToStr(item.getServiceEndTime(),DateUtils.DATE_FORMAT_YYYY_MM_DD);
                }
                vo.setEndTime("");*/
                String exDate = "";
                if (batchInfo.getExDate() != null) {
                    exDate = DateUtils.parseDateToStr(batchInfo.getExDate(), DateUtils.DATE_FORMAT_YYYY_MM_DD);
                }
                vo.setExDate(exDate);
                vo.setServiceYear(batchInfo.getServiceYear());
                if ("沃得".equals(factoryName)) {
                    vo.setFactory("CAAMS");//生产厂家
                }
                vo.setRemark("");//备注
                vo.setImei(item.getImei());//IMEI号
                voList.add(vo);
            }
        }
        String fileName = "obd_device_list_" + DateUtils.parseDateToStr(DateUtils.YYYYMMDD_HHMM, new Date());
        try {
            System.out.println("====voList :" + voList.size());
            ExcelUtil.writeExcel(response, voList, fileName, "OBD设备信息", new ExportDeviceListByBatchVO());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出失败，文件名:{}", fileName);
        }
    }


    @Log(title = "OBD终端管理 - 按批次导出维修设备信息", businessType = BusinessType.EXPORT, isSaveResponseData = false)
    @ApiOperation(value = "按批次导出维修设备信息")
    @PostMapping(value = "/exportRepairDeviceListByBatch")
    public void exportRepairDeviceListByBatch(@RequestBody @Valid ExportDeviceListByBatchDTO dto, HttpServletResponse response) throws BusinessException {
        List<ExportDeviceListByBatchVO> voList = new ArrayList<>();
        DeviceObdRepairExFactoryBatchInfo batchInfo = deviceObdRepairExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) return;
        String factoryName = batchInfo.getFactoryName();
//        String model = "TJ20-2";
        String model = "";
        GetDeviceObdBatchRepairRecordMappingInfoDO getDeviceObdBatchRepairRecordMappingInfoDO = new GetDeviceObdBatchRepairRecordMappingInfoDO();
        getDeviceObdBatchRepairRecordMappingInfoDO.setBatchId(batchInfo.getBatchId());
        getDeviceObdBatchRepairRecordMappingInfoDO.setSortRow("id");
        List<DeviceObdBatchRepairRecordMappingInfo> mappingList = deviceObdBatchRepairRecordMappingInfoService.getAllList(getDeviceObdBatchRepairRecordMappingInfoDO);
        if(!CollectionUtils.isEmpty(mappingList)) {
            GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
            getDeviceObdBaseInfoDO.setDtus(mappingList.stream().map(DeviceObdBatchRepairRecordMappingInfo::getDtu).collect(Collectors.toList()));
            getDeviceObdBaseInfoDO.setSortRow("createTime");
            List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
            if (baseList != null && baseList.size() > 0) {
                System.out.println("====baseList :" + baseList.size());
                for (DeviceObdBaseInfo item : baseList) {
                    ExportDeviceListByBatchVO vo = new ExportDeviceListByBatchVO();
                    vo.setDtuType("4G");//终端类型
                    String dtu = item.getDtu();
                    if (dtu.length() > 5) {
                        if ("道依茨法尔".equals(factoryName)) {//道依茨法尔
                            dtu = "NJY211023091" + dtu.substring(dtu.length() - 5, dtu.length());
                        } else if ("沃得".equals(factoryName)) {
                            dtu = "5600109" + dtu.substring(dtu.length() - 5, dtu.length());
                        }
                    }
                    vo.setDtu(dtu);//终端编号
                /*String model = "TJ20-2";
                if("道依茨法尔".equals(factoryName) || "沃得".equals(factoryName)){
                    model = "00109";
                }*/
                    vo.setModel(model);//终端型号
                    vo.setCommu("");//通信协议
                    vo.setSim(item.getSim());//sim卡号
                    //到期时间
//                vo.setEndTime(DateUtils.parseDateToStr(DateUtils.addDate(new Date(), 2, 0, 0, 0, 0, 0, 0), DateUtils.DATE_FORMAT_YYYY_MM_DD));
                    String simFactory = "";//SIM卡供應商和批次
                    SimInfo simInfo = simInfoService.getByImei(item.getSim());
                    if (simInfo != null) {
                        simFactory = simInfo.getSupplier() + "-" + simInfo.getBatch();
                    }
//                vo.setSimFactory(simFactory);
                    //到期時間
                /*String endTime = "";
                if(item.getServiceEndTime()!=null){
                    endTime = DateUtils.parseDateToStr(item.getServiceEndTime(),DateUtils.DATE_FORMAT_YYYY_MM_DD);
                }
                vo.setEndTime("");*/
                    String exDate = "";
                    if (batchInfo.getExDate() != null) {
                        exDate = DateUtils.parseDateToStr(batchInfo.getExDate(), DateUtils.DATE_FORMAT_YYYY_MM_DD);
                    }
                    vo.setExDate(exDate);
                    vo.setServiceYear(batchInfo.getServiceYear());
                    if ("沃得".equals(factoryName)) {
                        vo.setFactory("CAAMS");//生产厂家
                    }
                    vo.setRemark("");//备注
                    vo.setImei(item.getImei());//IMEI号
                    voList.add(vo);
                }
            }
        }
        String fileName = "obd_device_list_" + DateUtils.parseDateToStr(DateUtils.YYYYMMDD_HHMM, new Date());
        try {
            System.out.println("====voList :" + voList.size());
            ExcelUtil.writeExcel(response, voList, fileName, "OBD设备信息", new ExportDeviceListByBatchVO());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出失败，文件名:{}", fileName);
        }
    }

    @Log(title = "OBD终端管理-工况列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "工况列表")
    @PostMapping("/get25ObdList")
    public Result<PageResult<List<Get25ObdListVO>>> get25ObdList(@RequestBody @Valid Get25ObdListDTO dto) {
        List<String> dtuList = null;
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        if ((sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家 || sysUser.getUserType() == Constants.SysUserUserType.TYPE_TBOX生产厂家2) && !"testadmin".equals(sysUser.getName()) && sysUser.getUserId() != null) {
            dtuList = new ArrayList<>();
            dtuList.add("0");
            GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
            getDeviceObdBaseInfoDO.setFactoryUserId(sysUser.getUserId());
            getDeviceObdBaseInfoDO.setSortRow("id");
            List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
            if (baseList != null && baseList.size() > 0) {
                dtuList.addAll(baseList.stream().map(item -> item.getDtu()).collect(Collectors.toList()));
            }
        }
        List<Get25ObdListVO> voList = new ArrayList<>();
        GetDevice25ObdInfoDO getDevice25ObdInfoDO = new GetDevice25ObdInfoDO();
        getDevice25ObdInfoDO.setDtu(dto.getDtu());
        String tableName = "device_25_obd_info_";
        getDevice25ObdInfoDO.setPage(dto.getPage());
        getDevice25ObdInfoDO.setPageSize(dto.getPageSize());
        getDevice25ObdInfoDO.setSTime(dto.getStartTime());
        getDevice25ObdInfoDO.setETime(dto.getEndTime());
        tableName += dto.getStartTime().split(" ")[0].replaceAll("-", "");
        getDevice25ObdInfoDO.setSortRow("createTime");
        getDevice25ObdInfoDO.setSortOrder("desc");
        getDevice25ObdInfoDO.setTableName(tableName);
        if (dtuList != null && dtuList.size() > 0) {
            getDevice25ObdInfoDO.setDtuList(dtuList);
        }
        List<Device25ObdInfo> list = device25ObdInfoService.getPageList(getDevice25ObdInfoDO);
        if (list != null && list.size() > 0) {
            voList = EntityConversionUtil.copyList(list, Get25ObdListVO.class);
        }
        PageInfo<Device25ObdInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<Get25ObdListVO>> build = PageResult.<List<Get25ObdListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "OBD终端管理-获取升级包大小", businessType = BusinessType.INSERT)
    @ApiOperation(value = "获取升级包大小")
    @GetMapping("/getVersionFileSize")
    public Result<String> getVersionFileSize(@RequestParam String version) {
        String length = "";
        try {
            List<Device25ObdVersionInfo> list = deviceObdVersionInfoService.getByNewVersion(version);
            if (list == null || list.size()==0) {
                return Result.fail("9999", "版本号不存在");
            }
            Device25ObdVersionInfo info = list.get(0);
            File file = new File(info.getFilePath());
            if (file.exists() && file.isFile()) {
                length = file.length() + "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.suc(length);
    }

    @Log(title = "OBD终端管理-获取升级包分包数据", businessType = BusinessType.INSERT)
    @ApiOperation(value = "获取升级包分包数据")
    @GetMapping("/getVersionFileByPage")
    public Result<String> getVersionFileByPage(@RequestParam String version, @RequestParam Integer position) {
        String data = "";
        try {
            List<Device25ObdVersionInfo> list = deviceObdVersionInfoService.getByNewVersion(version);
            if (list == null || list.size()==0) {
                return Result.fail("9999", "版本号不存在");
            }
            Device25ObdVersionInfo info = list.get(0);
            byte[] bytes = FileUtils.getFileByte(info.getFilePath(), position);
            System.out.println("传之前长度 ： " + bytes.length);
            data = new String(bytes, "ISO8859-1");
            byte[] bytes1 = data.getBytes("ISO8859-1");
            System.out.println("传之后长度 ： " + bytes1.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.suc(data);
    }


    @Log(title = "OBD终端管理-版本列表", businessType = BusinessType.SELECT)
    @ApiOperation(value = "版本列表")
    @PostMapping("/getVersionList")
    public Result<PageResult<List<GetVersionListVO>>> getVersionList(@RequestBody @Valid GetVersionListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetVersionListVO> voList = new ArrayList<>();
        GetDeviceObdVersionInfoDO getDeviceObdVersionInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdVersionInfoDO.class);
        if (sysUser.getUserType() != 3) {//工厂配置帐号，可以看全部配置信息
            getDeviceObdVersionInfoDO.setSysUserId(sysUser.getSysUserId());
        }
        getDeviceObdVersionInfoDO.setSortRow("createTime");
        List<Device25ObdVersionInfo> list = deviceObdVersionInfoService.getPageList(getDeviceObdVersionInfoDO);
        if (list != null && list.size() > 0) {
            voList = EntityConversionUtil.copyList(list, GetVersionListVO.class);
        }
        PageInfo<Device25ObdVersionInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<GetVersionListVO>> build = PageResult.<List<GetVersionListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "OBD终端管理 - 导入设备编号在版本信息中", businessType = BusinessType.IMPORT)
    @ApiOperation(value = "导入设备编号在版本信息中")
    @PostMapping(value = "/importDeviceInVersion")
    public Result<String> importDeviceInVersion(@RequestParam("file") MultipartFile excelFile) {
        String dtus = "";
        List<ImportDeviceInVersionDTO> excelList = ExcelUtil.readExcel(excelFile, 1, 1, ImportDeviceInVersionDTO.class);
        if (StringUtils.isNull(excelList) || excelList.size() <= 0) {
            throw new BusinessException(ErrorCodeEnum.EXCEL_NOT_FOUNT);
        }
        List<ErrorBindFactoryVO> errorVoList = new ArrayList<>();
        List<DeviceObdBaseInfo> list = new ArrayList<>();
        System.out.println("excel总数：" + excelList.size());
        excelList = excelList.stream().filter(o -> {
            String dtu = o.getDtu();//Utils.verifyNullMember(o,"dtu");
            if ("".equals(dtu)) {
                errorVoList.add(EntityConversionUtil.copy(o, ErrorBindFactoryVO.class).errMsg("字段" + dtu + "为空"));
                log.error("字段{}为空", dtu);
                return false;
            }
            System.out.println("设备号：" + dtu);
            DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
            if (baseInfo == null) {
                errorVoList.add(EntityConversionUtil.copy(o, ErrorBindFactoryVO.class).errMsg("字段" + dtu + "该设备不存在"));
                log.error("字段{}设备不存在", dtu);
                return false;
            }
            list.add(baseInfo);
            return true;
        }).collect(Collectors.toList());
        if (list.size() > 0) {
            List<String> dtuList = list.stream().map(DeviceObdBaseInfo::getDtu).collect(Collectors.toList());
            dtus = String.join(";", dtuList);
        }
        if (!"".equals(dtus)) dtus += ";";
        return Result.suc(dtus);
    }

    /*@Log(title = "OBD终端管理-新增和修改版本信息（旧）", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增和修改版本信息")
    @PostMapping("/saveVersionInfo")
    public Result<Objects> saveVersionInfo(@RequestBody @Valid SaveVersionInfoDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        Device25ObdVersionInfo versionInfo = deviceObdVersionInfoService.getByNewVersion(dto.getNewVersion());
        if (versionInfo != null && versionInfo.getId() != dto.getId()) {
            return Result.fail("9999", "该版本号已经存在");
        }
        //当前用户为厂家配置，只能配置自己的设备升级
        if (sysUser.getUserType() == 4) {
            String errorDtus = "";
            if (dto.getDtus() != null && !"".equals(dto.getDtus())) {
                String[] dtuStr = dto.getDtus().split(";");
                for (String dtu : dtuStr) {
                    DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
                    if (baseInfo != null && baseInfo.getFactoryUserId() != sysUser.getUserId()) {
                        errorDtus += dtu + ";";
                    }
                }
                if (!"".equals(errorDtus)) {
                    return Result.fail("9999", "配置失败," + errorDtus + "设备不属于当前厂家");
                }
            }
        }
        String path = dto.getFilePath();
        String md5 = "";
        if (StringUtils.isNotBlank(path) && path.indexOf("upload") > -1) {
            int index = path.indexOf("upload");
            path = "/zhnl/ftp/" + path.substring(index, path.length());
            try {
                md5 = Md5Utils.getMd5ByFile(path);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        if (dto.getId() != null && dto.getId() != 0) {
            Device25ObdVersionInfo info = deviceObdVersionInfoService.getById(dto.getId());
            if (info == null) {
                return Result.fail("9999", "版本不存在");
            }
            info.setFilePath(path);
            info.setDtus(dto.getDtus());
            info.setNewVersion(dto.getNewVersion());
            info.setOldVersion(dto.getOldVersion());
            info.setContent(dto.getContent());
            info.setMd5(md5);
            info.setSysUserId(sysUser.getSysUserId());
            info.setStatus(0);
            deviceObdVersionInfoService.update(info);
        } else {
            Device25ObdVersionInfo info = new Device25ObdVersionInfo();
            info.setFilePath(path);
            info.setDtus(dto.getDtus());
            info.setNewVersion(dto.getNewVersion());
            info.setOldVersion(dto.getOldVersion());
            info.setContent(dto.getContent());
            info.setMd5(md5);
            info.setStatus(0);
            info.setSysUserId(sysUser.getSysUserId());
            deviceObdVersionInfoService.save(info);
        }
        return Result.suc();
    }*/
    @Log(title = "OBD终端管理-新增和修改版本信息（新）", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增和修改版本信息")
    @PostMapping("/saveVersionInfo")
    public Result<Objects> saveVersionInfo(@RequestBody @Valid SaveVersionInfoDTO dto) {
        String dtus1 = "";
        String dtus2 = "";
        List<List<Object>> list1 = new ArrayList<>();
        List<List<Object>> list2 = new ArrayList<>();
        try{
            String filePath1 = "";
            if (StringUtils.isNotBlank(dto.getFileUrl1()) && dto.getFileUrl1().indexOf("upload") > -1) {
                int index = dto.getFileUrl1().indexOf("upload");
                filePath1 = "/zhnl/ftp/" + dto.getFileUrl1().substring(index, dto.getFileUrl1().length());
            }
            String filePath2 = "";
            if (StringUtils.isNotBlank(dto.getFileUrl2()) && dto.getFileUrl2().indexOf("upload") > -1) {
                int index = dto.getFileUrl2().indexOf("upload");
                filePath2 = "/zhnl/ftp/" + dto.getFileUrl2().substring(index, dto.getFileUrl2().length());
            }

            File file1 = new File(filePath1);
            String fileName1 = filePath1.split("\\/")[filePath1.split("\\/").length-1];
            FileInputStream in1 =new FileInputStream(file1);
            list1 = ExcelUtil.getBankListByExcel(in1,fileName1);

            File file2 = new File(filePath2);
            String fileName2 = filePath2.split("\\/")[filePath2.split("\\/").length-1];
            FileInputStream in2 =new FileInputStream(file2);
            list2 = ExcelUtil.getBankListByExcel(in2,fileName1);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(CollectionUtils.isEmpty(list1) || CollectionUtils.isEmpty(list2)){
            return Result.fail("9999","文件为空");
        }
        for (int i=0;i<list1.size();i++) {
            List<Object> oList = list1.get(i);
            dtus1+=oList.get(0).toString();
            dtus1+=";";
        }
        for (int i=0;i<list2.size();i++) {
            List<Object> oList = list2.get(i);
            dtus2+=oList.get(0).toString();
            dtus2+=";";
        }
        if(!dtus1.equals(dtus2)){
            return Result.fail("9999","两份设备编号不一致");
        }
        String dtus = dtus1;
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        /*List<Device25ObdVersionInfo> list = deviceObdVersionInfoService.getByNewVersion(dto.getNewVersion());
        if(list!=null && list.size()>0){
            for(Device25ObdVersionInfo versionInfo:list){
                if (versionInfo != null && versionInfo.getId() != dto.getId()) {
                    return Result.fail("9999", "该版本号已经存在");
                }
            }
        }*/
        //当前用户为厂家配置，只能配置自己的设备升级
        if(sysUser.getUserType() == 4){
            String errorDtus = "";
            if(StringUtils.isNotBlank(dtus)){
                String[] dtuStr = dtus.split(";");
                for(String dtu : dtuStr){
                    DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
                    if(baseInfo!=null && baseInfo.getFactoryUserId()!= sysUser.getUserId()){
                        errorDtus+=dtu+";";
                    }
                }
                if(!"".equals(errorDtus)){
                    return Result.fail("9999","配置失败,"+errorDtus+"设备不属于当前厂家");
                }
            }
        }
        String path = dto.getFilePath();
        String md5 = "";
        if (StringUtils.isNotBlank(path) && path.indexOf("upload") > -1) {
            int index = path.indexOf("upload");
            path = "/zhnl/ftp/" + path.substring(index, path.length());
            try {
                md5 = Md5Utils.getMd5ByFile(path);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        if (dto.getId() != null && dto.getId() != 0) {
            Device25ObdVersionInfo info = deviceObdVersionInfoService.getById(dto.getId());
            if (info == null) {
                return Result.fail("9999", "版本不存在");
            }
            info.setFilePath(path);
            info.setDtus(dtus);
            info.setNewVersion(dto.getNewVersion());
            info.setOldVersion(dto.getOldVersion());
            info.setContent(dto.getContent());
            info.setMd5(md5);
            info.setSysUserId(sysUser.getSysUserId());
            info.setStatus(dto.getStatus());
            info.setFileUrl1(dto.getFileUrl1());
            info.setFileUrl2(dto.getFileUrl2());
            deviceObdVersionInfoService.update(info);
        } else {
            Device25ObdVersionInfo info = new Device25ObdVersionInfo();
            info.setFilePath(path);
            info.setDtus(dtus);
            info.setNewVersion(dto.getNewVersion());
            info.setOldVersion(dto.getOldVersion());
            info.setContent(dto.getContent());
            info.setMd5(md5);
            info.setStatus(dto.getStatus());
            info.setFileUrl1(dto.getFileUrl1());
            info.setFileUrl2(dto.getFileUrl2());
            info.setSysUserId(sysUser.getSysUserId());
            deviceObdVersionInfoService.save(info);
        }
        return Result.suc();
    }

    @Log(title = "OBD终端管理-删除版本信息", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除版本信息")
    @PostMapping("/deleteVersionInfo")
    public Result<Objects> deleteVersionInfo(@RequestBody @Valid DeleteVersionInfoDTO dto) {
        if (dto.getId() == null || dto.getId() == 0) {
            return Result.fail("9999", "参数有误");
        }
        Device25ObdVersionInfo info = deviceObdVersionInfoService.getById(dto.getId());
        if (info == null) {
            return Result.fail("9999", "版本不存在");
        }
        deviceObdVersionInfoService.delete(dto.getId());
        return Result.suc();
    }

    @Log(title = "OBD终端管理-工位机三码验证", businessType = BusinessType.DELETE)
    @ApiOperation(value = "工位机三码验证")
    @GetMapping("/vail3Code")
    public Result<Vail3CodeVO> vail3Code(@RequestParam String dtu, @RequestParam String imei, @RequestParam String sim) {
        Vail3CodeVO vo = new Vail3CodeVO();
        if (StringUtils.isBlank(dtu) || StringUtils.isBlank(imei) || StringUtils.isBlank(sim)) {
            vo.setStatus(false);
            vo.setMsg("设备编号或IMEI或SIM号为空");
            return Result.suc(vo);
        }
        vo = passCheck(dtu, sim, imei);
        return Result.suc(vo);
    }


    /**
     * 设备是否合格检测
     *
     * @param dtu
     * @param sim
     * @param imei
     * @return Map<Object>
     * @author tm
     * @date 2022-10-22 20:01
     */
    private Vail3CodeVO passCheck(String dtu, String sim, String imei) {
        Vail3CodeVO vo = new Vail3CodeVO();
        DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
        if (baseInfo == null) {
            vo.setStatus(false);
            vo.setMsg("设备不存在");
            return vo;
        }

        if (!StringUtils.isEmpty(sim) && !baseInfo.getSim().equals(sim)) {
            vo.setStatus(false);
            vo.setMsg("SIM编号不一致");
            return vo;
        }
        if (!StringUtils.isEmpty(imei) && !baseInfo.getImei().equals(imei)) {
            vo.setStatus(false);
            vo.setMsg("IMEI号不一致");
            return vo;
        }
        if (baseInfo.getBatchId() != null && baseInfo.getBatchId() != 0) {
            vo.setStatus(false);
            vo.setMsg("设备已出库");
            return vo;
        }
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setImei(imei);
        getDeviceObdBaseInfoDO.setSim(sim);
        getDeviceObdBaseInfoDO.setSortRow("id");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (baseList.size() > 1) {
            vo.setStatus(false);
            vo.setMsg("IMEI和SIM有重复");
            return vo;
        }
        if (baseInfo.getHasPass() == 0) {
            vo.setStatus(false);
            vo.setMsg("合盖前老化不合格");
            return vo;
        }
        if (baseInfo.getHasPass2() == null || baseInfo.getHasPass2() == 0) {
            vo.setStatus(false);
            vo.setMsg("合盖后老化不合格");
            return vo;
        }
        vo.setStatus(true);
        vo.setMsg("设备合格");
        return vo;
    }

    @Log(title = "OBD终端管理-统计当月服务卡到期设备信息", businessType = BusinessType.DELETE)
    @ApiOperation(value = "统计当月服务卡到期设备信息")
    @PostMapping("/statisticsSimExpireInfo")
    public Result<StatisticsSimExpireInfoVO> statisticsSimExpireInfo(@RequestBody @Valid StatisticsSimExpireInfoDTO dto) {
        StatisticsSimExpireInfoVO vo = new StatisticsSimExpireInfoVO();
        List<GetDeviceListVO> voList = new ArrayList<>();
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdBaseInfoDO.class);
        Date d = DateUtils.parseStrToDate(dto.getMonth(), DateUtils.DATE_FORMAT_YYYY_MM);
        int year = Integer.valueOf(DateUtils.getYear(d));
        int month = Integer.parseInt(DateUtils.getMonth(d));
        Date firstDate = DateUtils.getFirstDayOfMonth(year, month);
        Date lastDate = DateUtils.getLastDayOfMonth(year, month);
        getDeviceObdBaseInfoDO.setServiceStartTime(firstDate);
        getDeviceObdBaseInfoDO.setServiceEndTime(lastDate);
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        getDeviceObdBaseInfoDO.setSortOrder("desc");
        List<DeviceObdBaseInfo> deviceList = deviceObdBaseInfoService.selectSimExpireList(getDeviceObdBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            deviceList.forEach(item -> {
                GetDeviceListVO deviceVo = EntityConversionUtil.copy(item, GetDeviceListVO.class);
                deviceVo.setDeviceId(item.getId());
                voList.add(deviceVo);
            });
        }
        vo.setDeviceList(voList);
        PageInfo<DeviceObdBaseInfo> pageInfo = new PageInfo<>(deviceList);
        PageResult<List<GetDeviceListVO>> build = PageResult.<List<GetDeviceListVO>>builder().result(voList).pageInfo(pageInfo).build();
        vo.setTotal(build.getTotal() + "");
        return Result.suc(vo);
    }

    @Log(title = "OBD终端管理 - 绑定厂家", businessType = BusinessType.IMPORT)
    @ApiOperation(value = "绑定厂家")
    @PostMapping(value = "/bindFactory")
    public Result<BindFactoryVO> bindFactory(@RequestParam("file") MultipartFile excelFile, @RequestParam("factoryUserId") Long factoryUserId, @RequestParam("batchId") Long batchId) {
        List<BindFactoryDTO> excelList = ExcelUtil.readExcel(excelFile, 1, 1, BindFactoryDTO.class);
        if (StringUtils.isNull(excelList) || excelList.size() <= 0) {
            throw new BusinessException(ErrorCodeEnum.EXCEL_NOT_FOUNT);
        }
        List<ErrorBindFactoryVO> errorVoList = new ArrayList<>();
        List<DeviceObdBaseInfo> list = new ArrayList<>();
        System.out.println("excel总数：" + excelList.size());
        excelList = excelList.stream().filter(o -> {
            System.out.println("IMEI：" + o.getImei());
            String imei = o.getImei();//Utils.verifyNullMember(o,"dtu");
//            System.out.println("设备号："+dtu );
            if ("".equals(imei)) {
                errorVoList.add(EntityConversionUtil.copy(o, ErrorBindFactoryVO.class).errMsg("字段" + imei + "为空"));
                log.error("字段{}为空", imei);
                return false;
            }
            List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getByImei(imei);
            if (baseList == null) {
                errorVoList.add(EntityConversionUtil.copy(o, ErrorBindFactoryVO.class).errMsg("字段" + imei + "该设备不存在"));
                log.error("字段{}设备不存在", imei);
                return false;
            }
            if (baseList.size() > 1) {
                errorVoList.add(EntityConversionUtil.copy(o, ErrorBindFactoryVO.class).errMsg("字段" + imei + "有多条记录"));
                log.error("字段{}有多条记录", imei);
                return false;
            }
            DeviceObdBaseInfo baseInfo = baseList.get(0);
            if (baseInfo != null && baseInfo.getFactoryUserId() != null && baseInfo.getFactoryUserId() > 0) {
                errorVoList.add(EntityConversionUtil.copy(o, ErrorBindFactoryVO.class).errMsg("字段" + imei + "该设备已绑定厂家"));
                log.error("字段{}该设备已绑定厂家", imei);
                return false;
            }
            list.add(baseInfo);
            return true;
        }).collect(Collectors.toList());
        System.out.println("设备总数： " + list.size());
        List<DeviceObdBaseInfo> baseList = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        list.forEach(item -> {
            item.setFactoryUserId(factoryUserId);
            item.setLastModifiedTime(new Date());
            baseList.add(item);
            idList.add(item.getId() + "");
        });
        if (baseList.size() > 0) {
            deviceObdBaseInfoService.updateList(baseList);
            String factoryName = "";
            UserInfo userInfo = userInfoService.getById(factoryUserId);
            if (userInfo != null) factoryName = userInfo.getName();
            DeviceObdExFactoryBatchBindInfo bindInfo = new DeviceObdExFactoryBatchBindInfo();
            bindInfo.setFactoryUserId(factoryUserId);
            bindInfo.setBatchId(batchId);
            bindInfo.setNumber(idList.size());
            String dtus = String.join(";", idList);
            bindInfo.setDtus(dtus);
            bindInfo.setFactoryName(factoryName);
            deviceObdExFactoryBatchBindInfoService.save(bindInfo);
        }
        return Result.suc(BindFactoryVO.builder().importSuccess(baseList.size()).errorList(errorVoList).build());
    }


    @Log(title = "OBD终端管理-获取批次绑定记录列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "获取批次绑定记录列表")
    @PostMapping("/getBindListByBatchId")
    public Result<PageResult<List<GetBindListByBatchIdVO>>> getBindListByBatchId(@RequestBody @Valid GetBindListByBatchIdDTO dto) {
        List<GetBindListByBatchIdVO> voList = new ArrayList<>();
        GetDeviceObdExFactoryBatchBindInfoDO getDeviceObdExFactoryBatchBindInfoDO = EntityConversionUtil.copy(dto, GetDeviceObdExFactoryBatchBindInfoDO.class);
        getDeviceObdExFactoryBatchBindInfoDO.setSortRow("createTime");
        List<DeviceObdExFactoryBatchBindInfo> bindList = deviceObdExFactoryBatchBindInfoService.getPageList(getDeviceObdExFactoryBatchBindInfoDO);
        if (bindList != null && bindList.size() > 0) {
            voList = EntityConversionUtil.copyList(bindList, GetBindListByBatchIdVO.class);
        }
        PageInfo<DeviceObdExFactoryBatchBindInfo> pageInfo = new PageInfo<>(bindList);
        PageResult<List<GetBindListByBatchIdVO>> build = PageResult.<List<GetBindListByBatchIdVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "OBD终端管理 -  导出绑定的设备列表", businessType = BusinessType.EXPORT, isSaveResponseData = false)
    @ApiOperation(value = "导出绑定的设备列表")
    @PostMapping(value = "/exportBindDeviceList")
    public void exportBindDeviceList(@RequestBody @Valid ExportBindDeviceListDTO dto, HttpServletResponse response) throws BusinessException {
        List<ExportBindDeviceListVO> voList = new ArrayList<>();
        DeviceObdExFactoryBatchBindInfo bindInfo = deviceObdExFactoryBatchBindInfoService.getById(dto.getId());
        if (bindInfo == null) return;
        DeviceObdExFactoryBatchInfo batchInfo = deviceObdExFactoryBatchInfoService.getById(bindInfo.getBatchId());
//        String model = "TJ20-2";
        String model = "";
        if (batchInfo.getModelId() != null && batchInfo.getModelId() != 0) {
            SystemDeviceModelInfo modelInfo = systemDeviceModelInfoService.getById(batchInfo.getModelId());
            if (modelInfo != null) model = modelInfo.getName();
        }
        if (bindInfo.getDtus() == null || "".equals(bindInfo.getDtus())) return;
        String[] dtuStr = bindInfo.getDtus().split(";");
        List<Long> ids = new ArrayList<>();
        for (String dtu : dtuStr) {
            if ("".equals(dtu)) continue;
            ids.add(Long.valueOf(dtu));
        }
        if (ids.size() == 0) return;
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setIds(ids);
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (baseList != null && baseList.size() > 0) {
            System.out.println("====baseList :" + baseList.size());
            for (DeviceObdBaseInfo item : baseList) {
                ExportBindDeviceListVO vo = new ExportBindDeviceListVO();
                vo.setFactoryCode("");//终端类型
                vo.setImei(item.getImei());//IMEI号
                vo.setModelName(model);
                vo.setDtu(item.getDtu());
                vo.setMachineCode("");
                voList.add(vo);
            }
        }
        String fileName = "obd_device_list_" + DateUtils.parseDateToStr(DateUtils.YYYYMMDD_HHMM, new Date());
        try {
            System.out.println("====voList :" + voList.size());
            ExcelUtil.writeExcel(response, voList, fileName, "OBD设备信息", new ExportBindDeviceListVO());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出失败，文件名:{}", fileName);
        }
    }


    @Log(title = "OBD终端管理 -  根据纸箱号导入设备列表", businessType = BusinessType.EXPORT, isSaveResponseData = false)
    @ApiOperation(value = "根据纸箱号导入设备列表")
    @PostMapping(value = "/exportDeviceListByCarton")
    public void exportDeviceListByCarton(@RequestBody @Valid ExportDeviceListByCartonDTO dto, HttpServletResponse response) throws BusinessException {
        List<ExportDeviceListByCartonVO> voList = new ArrayList<>();

        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setCartonNo(dto.getCartonNo());
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (baseList != null && baseList.size() > 0) {
            voList = EntityConversionUtil.copyList(baseList, ExportDeviceListByCartonVO.class);
        }
        String fileName = "obd_device_list_" + DateUtils.parseDateToStr(DateUtils.YYYYMMDD_HHMM, new Date());
        try {
            System.out.println("====voList :" + voList.size());
            ExcelUtil.writeExcel(response, voList, fileName, "OBD设备信息", new ExportDeviceListByCartonVO());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出失败，文件名:{}", fileName);
        }
    }

    @Log(title = "OBD终端管理-找附近的设备", businessType = BusinessType.DELETE)
    @ApiOperation(value = "找附近的设备")
    @PostMapping("/searchNearDevice")
    public Result<List<SearchNearDeviceVO>> searchNearDevice(@RequestBody @Valid SearchNearDeviceDTO dto) {
        List<SearchNearDeviceVO> voList = new ArrayList<>();
        DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dto.getDtu());
        if (baseInfo == null) {
            return Result.fail("9999", "设备不存在");
        }
        if (baseInfo.getLon() != null && baseInfo.getLat() != null) {
            double lon1 = Double.parseDouble(baseInfo.getLon());
            double lat1 = Double.parseDouble(baseInfo.getLat());
            GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
            getDeviceObdBaseInfoDO.setFactoryUserId(733l);
            getDeviceObdBaseInfoDO.setSortRow("dataTime");
            getDeviceObdBaseInfoDO.setSortOrder("desc");
            List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
            List<String> dtus = baseList.stream().map(DeviceObdBaseInfo::getDtu).collect(Collectors.toList());
            Map<String, DeviceObdBaseInfo> dtuMap = baseList.stream().collect(Collectors.toMap(DeviceObdBaseInfo::getDtu, Function.identity()));
            GetDeviceObdWorkDailyRecordInfoDO getDeviceObdWorkDailyRecordInfoDO = new GetDeviceObdWorkDailyRecordInfoDO();
            getDeviceObdWorkDailyRecordInfoDO.setDtus(dtus);
            getDeviceObdWorkDailyRecordInfoDO.setArea(20f);
            List<DeviceObdWorkDailyRecordInfo> recordList = deviceObdWorkDailyRecordInfoService.getAllList(getDeviceObdWorkDailyRecordInfoDO);
            if (recordList != null && recordList.size() > 0) {
                for (DeviceObdWorkDailyRecordInfo info : recordList) {
                    if (info.getDtu().equals(dto.getDtu())) continue;
                    if (info.getLng() != null && info.getLat() != null && info.getLng() > 0 && info.getLat() > 0) {
                        double lon2 = info.getLng();
                        double lat2 = info.getLat();
                        double distance = PositionUtil.getDistance3(lon1, lat1, lon2, lat2) / 1000;
                        if (distance < 50) {
                            SearchNearDeviceVO vo = EntityConversionUtil.copy(info, SearchNearDeviceVO.class);
                            vo.setDistance(distance);
                            DeviceObdBaseInfo baseInfo1 = dtuMap.get(info.getDtu());
                            vo.setImei(baseInfo1.getImei());
                            vo.setSim(baseInfo1.getSim());
                            voList.add(vo);
                        }
                    }
                }
            }
            /*for (DeviceObdBaseInfo info : baseList) {
                if (info.getDtu().equals(dto.getDtu())) continue;
                if (info.getLon() != null && info.getLat() != null && !"".equals(info.getLon()) && !"0.0".equals(info.getLon()) && !"0".equals(info.getLon())) {
                    double lon2 = Double.parseDouble(info.getLon());
                    double lat2 = Double.parseDouble(info.getLat());
                    double distance = PositionUtil.getDistance3(lon1, lat1, lon2, lat2) / 1000;
                    if (distance < 50) {
                        SearchNearDeviceVO vo = EntityConversionUtil.copy(info, SearchNearDeviceVO.class);
                        vo.setDistance(distance);
                        voList.add(vo);
                    }
                }
            }*/
            voList.sort(Comparator.comparing(SearchNearDeviceVO::getDistance));
        }
        return Result.suc(voList);
    }

    @Log(title = "OBD终端管理-查询设备升级情况", businessType = BusinessType.DELETE)
    @ApiOperation(value = "查询设备升级情况")
    @PostMapping("/searchUpdateInfo")
    public Result<SearchUpdateInfoVO> searchUpdateInfo(@RequestBody @Valid SearchUpdateInfoDTO dto) {
        SearchUpdateInfoVO searchUpdateInfoVO = new SearchUpdateInfoVO();
        List<SearchUpdateInfoDeviceVO> voList = new ArrayList<>();
        int total = 0;
        int finish = 0;
        int noFinish = 0;
        Device25ObdVersionInfo versionInfo = deviceObdVersionInfoService.getById(dto.getId());
        if (versionInfo != null) {
            String dtus = versionInfo.getDtus();
            if (dtus != null && !"".equals(dtus)) {
                dtus = dtus.substring(0, dtus.length() - 1);
                String[] dtuStr = dtus.split(";");
                List<String> dtuList = Arrays.asList(dtuStr);
                GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
                getDeviceObdBaseInfoDO.setDtus(dtuList);
                getDeviceObdBaseInfoDO.setSortRow("id");
                getDeviceObdBaseInfoDO.setNoNewVersion(versionInfo.getNewVersion());
                List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
                total = dtuStr.length;
//                List<DeviceObdBaseInfo> finishList= new ArrayList<>();
                List<DeviceObdBaseInfo> noFinishList = new ArrayList<>();
                if (baseList != null && baseList.size() > 0) {
                    noFinish = baseList.size();
                    if (baseList.size() > 50)
                        noFinishList = baseList.subList(0, 51);
                    else
                        noFinishList = baseList;
                    /*for (DeviceObdBaseInfo baseInfo : baseList) {
                        if (baseInfo != null) {
                            if (versionInfo.getNewVersion().equals(baseInfo.getCurVersion())) {
                                finishList.add(baseInfo);
                            } else {
                                noFinishList.add(baseInfo);
                            }
                        }
                    }*/
                }
                finish = total - noFinish;
                if (noFinishList != null && noFinishList.size() > 0) {
                    voList = EntityConversionUtil.copyList(noFinishList, SearchUpdateInfoDeviceVO.class);
                   /* noFinishList.forEach(item->{
                        SearchUpdateInfoDeviceVO vo = EntityConversionUtil.copy(item,SearchUpdateInfoDeviceVO.class);
                        vo.setDeviceId(item.getId());
                        vo.setStatus(0);
                        voList.add(vo);
                    });*/
                }

                /*if(finishList!=null && finishList.size()>0){
                    finishList.forEach(item->{
                        SearchUpdateInfoDeviceVO vo = EntityConversionUtil.copy(item,SearchUpdateInfoDeviceVO.class);
                        vo.setDeviceId(item.getId());
                        vo.setStatus(1);
                        voList.add(vo);
                    });
                }*/
            }
        }
        searchUpdateInfoVO.setTotal(total);
        searchUpdateInfoVO.setFinish(finish);
        searchUpdateInfoVO.setNoFinish(noFinish);
        searchUpdateInfoVO.setDeviceList(voList);
        return Result.suc(searchUpdateInfoVO);
    }


    @Log(title = "OBD终端管理-扫码查询设备升级情况", businessType = BusinessType.SELECT)
    @ApiOperation(value = "扫码查询设备升级情况")
    @PostMapping("/scanUpdateInfo")
    public Result<ScanUpdateInfoVO> scanUpdateInfo(@RequestBody @Valid ScanUpdateInfoDTO dto) {
        ScanUpdateInfoVO vo = new ScanUpdateInfoVO();
        int status = 0;
        Device25ObdVersionInfo versionInfo = deviceObdVersionInfoService.getById(dto.getId());
        if (versionInfo == null) {
            return Result.fail("9999", "没有该升级版本");
        }
        if (dto.getDtu() == null || "".equals(dto.getDtu()) || dto.getDtu().length() < 5) {
            return Result.fail("9999", "设备不存在");
        }
        if (versionInfo.getDtus() == null || "".equals(versionInfo.getDtus())) {
            return Result.fail("9999", "该升级未配设备");
        }
        String dtus = versionInfo.getDtus().substring(0, versionInfo.getDtus().length() - 1);
        String[] dtuStr = dtus.split(";");
        String shortDtu = dto.getDtu().substring(dto.getDtu().length() - 5, dto.getDtu().length());
        String dtu = "";
        for (String d : dtuStr) {
            if (d.indexOf(shortDtu) > -1) {
                dtu = d;
                break;
            }
        }
        if ("".equals(dtu)) {
            return Result.fail("9999", "设备不存在或未配置");
        }
        DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dtu);
        if (baseInfo == null) {
            return Result.fail("9999", "设备不存在");
        }
        if (baseInfo.getCurVersion().equals(versionInfo.getNewVersion())) {
            status = 1;
        }
        vo.setStatus(status);
        return Result.suc(vo);
    }

    @Log(title = "OBD终端管理-APP扫码查询设备升级情况", businessType = BusinessType.SELECT)
    @ApiOperation(value = "APP扫码查询设备升级情况")
    @GetMapping("/scanUpdateInfoInApp")
    public Result<ScanUpdateInfoInAppVO> scanUpdateInfoInApp(@RequestParam String sdtu1, @RequestParam String prefix, @RequestParam String newVersion) {
        ScanUpdateInfoInAppVO vo = new ScanUpdateInfoInAppVO();
        if (org.springframework.util.StringUtils.isEmpty(prefix)) {
            vo.setStatus(false);
            vo.setMsg("前缀不能为空");
            return Result.suc(vo);
        }
        if (org.springframework.util.StringUtils.isEmpty(sdtu1)) {
            vo.setStatus(false);
            vo.setMsg("设备号不能为空");
            return Result.suc(vo);
        }
        String dtu = "";
        if (sdtu1.length() > 5) dtu = prefix + sdtu1.substring(sdtu1.length() - 5, sdtu1.length());
        if (org.springframework.util.StringUtils.isEmpty(dtu)) {
            vo.setStatus(false);
            vo.setMsg("设备号有误");
            return Result.suc(vo);
        }
        List<GetDeviceListVO> list = new ArrayList<>();
        DeviceObdBaseInfo info = deviceObdBaseInfoService.getByDtu(dtu);
        if (info == null) {
            vo.setStatus(false);
            vo.setMsg("设备不存在");
            return Result.suc(vo);
        }
        GetDeviceListVO deviceVo = EntityConversionUtil.copy(info, GetDeviceListVO.class);
        list.add(deviceVo);
        vo.setList(list);
        GetDeviceObdTcpLogInfoDO getDeviceObdTcpLogInfoDO = new GetDeviceObdTcpLogInfoDO();
        getDeviceObdTcpLogInfoDO.setDtu(dtu);
        getDeviceObdTcpLogInfoDO.setMsgType("500");
        getDeviceObdTcpLogInfoDO.setPage(1);
        getDeviceObdTcpLogInfoDO.setPageSize(1);
        getDeviceObdTcpLogInfoDO.setSortRow("createTime");
        getDeviceObdTcpLogInfoDO.setSortOrder("desc");
        List<DeviceObdTcpLogInfo> objectList = deviceObdTcpLogInfoService.getPageList(getDeviceObdTcpLogInfoDO);
        String c = "";
        if (objectList != null && objectList.size() > 0) {
            DeviceObdTcpLogInfo tcpMap = objectList.get(0);
            c = tcpMap.getContent();
        }
        vo.setContent(c);
        System.out.println("========prefix : " + prefix);
        if (info.getHasPass() == 0) {
            vo.setStatus(false);
            vo.setMsg("老化不合格");
        }
//        else if(info.getCjzt() == 0 && !"02al9900".equals(prefix) && !"02ak9900".equals(prefix)){
//            System.out.println("========prefix : " + "02al9900".equals(prefix));
//            map.put("status",false);
//            map.put("msg","拆机状态未变动");
//        }
        else {
            vo.setStatus(true);
            vo.setMsg("成功");
        }

        //设备未升的话，查询页码信息
        Map<String, Object> page = new HashMap<>();
        if (!newVersion.equals(info.getCurVersion())) {
            page.put("totalPage", "107");
            getDeviceObdTcpLogInfoDO.setMsgType("504");
            List<DeviceObdTcpLogInfo> tcpList = deviceObdTcpLogInfoService.getPageList(getDeviceObdTcpLogInfoDO);
            if (tcpList == null || tcpList.size() == 0) {
                page.put("curPage", "");
            } else {
                DeviceObdTcpLogInfo tcpMap = tcpList.get(0);
                String content = tcpMap.getContent();
                page.put("curPage", content.split("\\|")[2]);
            }
        }
        vo.setPage(page);
        return Result.suc(vo);
    }

    @Log(title = "OBD终端管理-测试生成发送gps文件", businessType = BusinessType.SELECT)
    @ApiOperation(value = "测试生成发送gps文件")
    @PostMapping("/createGpsFile")
    public Result<String> createGpsFile(@RequestBody @Valid CreateGpsFileDTO dto) {
        String url = "";
        GetDataObdTcpLogInfoDO getDataObdTcpLogInfoDO = EntityConversionUtil.copy(dto, GetDataObdTcpLogInfoDO.class);
        getDataObdTcpLogInfoDO.setSortRow("gpsTime");
        getDataObdTcpLogInfoDO.setDateStr(dto.getDate());
        List<DataObdTcpLogInfo> tcpList = dataObdTcpLogInfoService.selectErrorPageList(getDataObdTcpLogInfoDO);
        String filePath = UploadConfig.getFilePath();
        String fileName = IdUtils.fastUUID() + ".txt";
        String pathFileName = "/zhnl/ftp/upload/gps/" + fileName;
//        pathFileName = "d:/test/"+fileName;
        if (tcpList != null && tcpList.size() > 0) {
            for (DataObdTcpLogInfo tcp : tcpList) {
                if (tcp.getGpsContent() != null && !"".equals(tcp.getGpsContent())) {
                    String m = tcp.getDtu() + "," + tcp.getImei() + ",," + tcp.getZcgzsj();
                    FileUtils.writeFile(m, pathFileName);
                    FileUtils.writeFile(tcp.getGpsContent(), pathFileName);
                }
            }
            url = "http://file.zhihuinonglin.com:8866/upload/gps/" + fileName;
        }
        return Result.suc(url);
    }

    @Log(title = "OBD终端管理-大田IP列表", businessType = BusinessType.SELECT)
    @ApiOperation(value = "大田IP列表")
    @PostMapping("/getDatianIPList")
    public Result<PageResult<List<GetDatianIPListVO>>> getDatianIPList(@RequestBody @Valid GetDatianIPListDTO dto) {
        List<GetDatianIPListVO> voList = new ArrayList<>();
        GetDevice25ObdIpMonitorInfoDO getDevice25ObdIpMonitorInfoDO = EntityConversionUtil.copy(dto, GetDevice25ObdIpMonitorInfoDO.class);
        getDevice25ObdIpMonitorInfoDO.setSortRow("createTime");
        List<Device25ObdIpMonitorInfo> ipList = device25ObdIpMonitorInfoService.getPageList(getDevice25ObdIpMonitorInfoDO);
        if (ipList != null && ipList.size() > 0) {
            voList = EntityConversionUtil.copyList(ipList, GetDatianIPListVO.class);
        }
        PageInfo<Device25ObdIpMonitorInfo> pageInfo = new PageInfo<>(ipList);
        PageResult<List<GetDatianIPListVO>> build = PageResult.<List<GetDatianIPListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "OBD终端管理-APP获取升级配置列表信息", businessType = BusinessType.SELECT)
    @ApiOperation(value = "APP获取升级配置列表信息")
    @GetMapping("/getVersionListInAPP")
    public Result<List<GetVersionListInAPPVO>> getVersionListInAPP() {
        List<GetVersionListInAPPVO> voList = new ArrayList<>();
        GetDeviceObdVersionInfoDO getDeviceObdVersionInfoDO = new GetDeviceObdVersionInfoDO();
        getDeviceObdVersionInfoDO.setStatus(1);
        getDeviceObdVersionInfoDO.setSortRow("createTime");
        List<Device25ObdVersionInfo> list = deviceObdVersionInfoService.getAllList(getDeviceObdVersionInfoDO);
        if (list != null && list.size() > 0) {
            voList = EntityConversionUtil.copyList(list, GetVersionListInAPPVO.class);
        }
        return Result.suc(voList);
    }

    @Log(title = "OBD终端管理-APP扫箱码查询设备升级情况", businessType = BusinessType.SELECT)
    @ApiOperation(value = "APP扫箱码查询设备升级情况")
    @GetMapping("/scanCartonNoUpdateInfoInApp")
    public Result<List<ScanCartonNoUpdateInfoInAppVO>> scanCartonNoUpdateInfoInApp(@RequestParam String cartonNo, @RequestParam Long versionId) {
        List<ScanCartonNoUpdateInfoInAppVO> voList = new ArrayList<>();
        List<ScanCartonNoUpdateInfoInAppVO> voList2 = new ArrayList<>();
        if (org.springframework.util.StringUtils.isEmpty(cartonNo)) {
            return Result.fail("9999", "箱号不能为空");
        }
        Device25ObdVersionInfo versionInfo = deviceObdVersionInfoService.getById(versionId);
        if (versionId == null) {
            return Result.fail("9999", "当前升级版本不存在");
        }
        String newVersion = versionInfo.getNewVersion();
        List<GetDeviceListVO> list = new ArrayList<>();
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setCartonNo(cartonNo);
        getDeviceObdBaseInfoDO.setSortRow("id");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        if (baseList == null || baseList.size() == 0) {
            return Result.fail("9999", "当前箱号中没有设备");
        }
        int totalPage = 0;
        try {
            byte[] byteData = FileUtils.readFileByBytes(versionInfo.getFilePath());
            int size = 1024;
            int totalSize = byteData.length;
            if (totalSize % size == 0) {
                totalPage = totalSize / size;
            } else {
                totalPage = totalSize / size + 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (DeviceObdBaseInfo info : baseList) {
            ScanCartonNoUpdateInfoInAppVO vo = new ScanCartonNoUpdateInfoInAppVO();
            String dtu = info.getDtu();
            GetDeviceListVO deviceVo = EntityConversionUtil.copy(info, GetDeviceListVO.class);
//            list.add(deviceVo);
            vo.setDeviceVo(deviceVo);
            GetDeviceObdTcpLogInfoDO getDeviceObdTcpLogInfoDO = new GetDeviceObdTcpLogInfoDO();
            getDeviceObdTcpLogInfoDO.setDtu(dtu);
            getDeviceObdTcpLogInfoDO.setMsgType("500");
            getDeviceObdTcpLogInfoDO.setPage(1);
            getDeviceObdTcpLogInfoDO.setPageSize(1);
            getDeviceObdTcpLogInfoDO.setSortRow("createTime");
            getDeviceObdTcpLogInfoDO.setSortOrder("desc");
            List<DeviceObdTcpLogInfo> objectList = deviceObdTcpLogInfoService.getPageList(getDeviceObdTcpLogInfoDO);
            String c = "";
            if (objectList != null && objectList.size() > 0) {
                DeviceObdTcpLogInfo tcpMap = objectList.get(0);
                c = tcpMap.getContent();
            }
            vo.setContent(c);
            if (info.getHasPass() == 0) {
                vo.setStatus(false);
                vo.setMsg("老化不合格");
            } else {
                vo.setStatus(true);
                vo.setMsg("成功");
            }

            //设备未升的话，查询页码信息
            Map<String, Object> page = new HashMap<>();
            if (!newVersion.equals(info.getCurVersion())) {
                int tP = totalPage - 1;
                page.put("totalPage", tP + "");
                getDeviceObdTcpLogInfoDO.setMsgType("504");
                List<DeviceObdTcpLogInfo> tcpList = deviceObdTcpLogInfoService.getPageList(getDeviceObdTcpLogInfoDO);
                if (tcpList == null || tcpList.size() == 0) {
                    page.put("curPage", "");
                } else {
                    DeviceObdTcpLogInfo tcpMap = tcpList.get(0);
                    String content = tcpMap.getContent();
                    page.put("curPage", content.split("\\|")[2]);
                }
            }
            vo.setPage(page);
            if (deviceVo.getCurVersion().equals(versionInfo.getNewVersion())) {
                voList2.add(vo);
            } else voList.add(vo);
        }
        if (voList2.size() > 0) voList.addAll(voList2);
        return Result.suc(voList);
    }

    @Log(title = "OBD终端管理-发送联调数据给环保部", businessType = BusinessType.SELECT)
    @ApiOperation(value = "发送联调数据给环保部")
    @GetMapping("/sendGpsToFk")
    public Result<Objects> sendGpsToFk() {
        String tableName = "device_obd_gps_info_20230531";
        GetDeviceObdGpsInfoDO getDeviceObdGpsInfoDO = new GetDeviceObdGpsInfoDO();
        getDeviceObdGpsInfoDO.setTableName(tableName);
        getDeviceObdGpsInfoDO.setSortRow("time");
        getDeviceObdGpsInfoDO.setSortOrder("asc");
        getDeviceObdGpsInfoDO.setDtu("02ai990005748");
        getDeviceObdGpsInfoDO.setIsEffective("1");
        List<DeviceObdGpsInfo> gpsList = deviceObdGpsInfoService.getAllList(getDeviceObdGpsInfoDO);
        int index = 0;
        for(int i=0;i<gpsList.size();i++){
            if(i<180)continue;
            DeviceObdGpsInfo info = gpsList.get(i);
//            if(info.getId() <6060300) continue;
            SocketTest.sendGps(info.getLon(),info.getLat());
            try{
                Thread.sleep(5000);
            }catch (Exception e){
                e.printStackTrace();
            }
            if(index==200){
                SocketTest.loginInOfMachine();
            }
            if(index == 300){
                SocketTest.loginOutOfMachine();
            }
            if(index==400){
                SocketTest.loginOut();
            }

            if(index==580){
                SocketTest.sendTamperAlarm(info.getLon(),info.getLat());
            }
            index++;
        }
        return Result.suc();
    }
    @Log(title = "OBD终端管理-修改大田IP状态", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改大田IP状态")
    @PostMapping("/updateDatianIPStatus")
    public Result<Objects> updateDatianIPStatus(@RequestBody @Valid UpdateDatianIPStatusDTO dto) {
        Device25ObdIpMonitorInfo ipInfo = device25ObdIpMonitorInfoService.getById(dto.getId());
        if (ipInfo == null) {
            return Result.fail("9999", "记录不存在");
        }
        ipInfo.setStatus(1);
        device25ObdIpMonitorInfoService.update(ipInfo);
        return Result.suc();
    }
}
